Search code examples
c#cameratransformpositioningmath-functions

Using Mathf.Clamp without effecting y axis.


I have a script that makes my camera follow the mouse. Works fine but I want the camera to only be able to move so far so I used this.

transform.position = new Vector3(Mathf.Clamp(transform.position.x, 1.5f, -1.4f), 0, -10);

It works to stop the camera from moving too far on the x axis but it also froze the y axis completely. I tried using another Mathf.Clamp again using transform.position.y but it made no difference. Anyone know how to fix this?


Solution

  • Assuming you want the same values for y and z that you already have:

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

    This way you're only changing the x value.