Simple doubt of C# in Unity

Asked

Viewed 122 times

1

I don’t know anything about C#, but I’m trying to develop a simple project in Unity. It consists of moving a crane. I made 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);
        }  
    }
}
  • And what are these two points? They’re arbitrary, they’re up to the end of the camera view, or something else?

  • That’s two points I want to arbitrate on. As seen in the code it only moves by the X axis and, I want it to go at most up to -5 of the X axis up to 6 of the X axis.

1 answer

2

Use Mathf.Clamp to restrict the movement of the object.

transform.position = new Vector3 (Mathf.Clamp(transform.position.x, -5f, 6f),transform.position.y, transform.position.z);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.