0

I use this script rotate the camera on its local X axis:

 float v = verticalSpeed * Input.GetAxis("Mouse Y");
 transform.Rotate(-v, 0, 0);

Right now this lets the player look up & down without limit, wrapping around a full 360 degrees. How can I limit this so they can look only 90 degrees up or 90 degrees down from the horizon?

DMGregory
  • 134,153
  • 22
  • 242
  • 357
NADER LABBAD
  • 47
  • 1
  • 9

2 Answers2

0

You can use if condition such as:

float v = verticalSpeed * Input.GetAxis("Mouse Y");
if (v > 100)  then //100 your limit
    {v= 50}
else 
    {v=30}

or you can use math.sign function which gives you +1,0,-1

if the result for your case v > 0 it returns +1

if it is zero than 0

if it is negative then it is -1

you can limit your camera by that way.

0

This is a straightforward application of Mathf.Clamp(value, min, max). Ordinarily I'd recommend caution calculating new orientations from Euler angles, but for camera orientation it's typically safe enough. You might want to pull back slightly from 90, say 80 degrees, so you don't hit nasty behaviour right at the poles.

// Correct for deltaTime so your behaviour is framerate independent.
// (You may need to increase your speed as it's now measured in degrees per second, not per frame)
float angularIncrement = verticalSpeed * Input.GetAxis("Mouse Y") * Time.deltaTime;

// Get the current rotation angles.
Vector3 eulerAngles = transform.localEulerAngles;

// Returned angles are in the range 0...360. Map that back to -180...180 for convenience.
if(eulerAngles.x > 180f)
    eulerAngles.x -= 360f;

// Increment the pitch angle, respecting the clamped range.
eulerAngles.x = Mathf.Clamp(eulerAngles.x - angularIncrement, -90f, 90f);

// Orient to match the new angles.
transform.localEulerAngles = eulerAngles;
DMGregory
  • 134,153
  • 22
  • 242
  • 357