Simple C # doubt on Unity

1

I do not know anything about C #, but I'm trying to develop a simple project on Unity. It consists of moving a crane. I did the code to move the bridge, but if I keep holding the button it keeps moving beyond the limit.

How can I limit the movement between two points, in this case, of the X axis since it only moves in it.

Here is the code:

public class MoveBarra : MonoBehaviour {
    public float VelocidadeMov;

    void Start () {
        VelocidadeMov = .25f;
    }

    void Update() {
        if(Input.GetKey(KeyCode.W))
        {
            transform.Translate(-VelocidadeMov, 0, 0);
        }
        if (Input.GetKey(KeyCode.S))
        {
            transform.Translate(VelocidadeMov, 0, 0);
        }  
    }
}
    
asked by anonymous 01.11.2016 / 10:50

1 answer

2

Use Mathf.Clamp to restrict object movement.

transform.position = new Vector3 (Mathf.Clamp(transform.position.x, -5f, 6f),transform.position.y, transform.position.z);
    
02.11.2016 / 00:20