Hello everyone Iam a beginner in Unity and Iam trying to make some Pong like game but I have this problem. For some reason when I try to stop at Y position 3.748 it doesn’t work and the player/platform goes beyond it. Here is the code. I tried putting it in “void FixedUpdate ()” but that doesn’t do anything.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player1 : MonoBehaviour {
public float speed = 10;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (transform.position.y < 3.748f)
{
transform.Translate(Vector3.up * Time.deltaTime * Input.GetAxis("Vertical") * speed);
}
}
}
For starters, doing it the way you’re hoping to do it, if it worked, would simply disable all controls after you went outside that range, and you’d never be able to get back out.
There are a few different approaches. I’d suggest clamping your Y position (I assume that you will have an upper bound as well?). Something like this:
Sidenote: It’s weird that your current code DOESN’T work - in the sense of “it should be stopping all movement after that point” - which makes me think that there’s another issue. Maybe you’re looking at the objects .localPosition (as seen in the inspector) and not the world position, for example? Try Debug.Log(transform.position) to see what that value is.
Wow thank you so much it works, but I had to edit that code because the player was only being able to move outside of the screen. This is the code now.