- Home /
I can't figure out how to clamp it
I can't figure out how to clamp my camera rotation.
float CurY = Input.GetAxisRaw("Mouse X");
Vector3 RotateY = new Vector3(0f, CurY, 0f) * TurnSpeed;
float CurX = Input.GetAxisRaw("Mouse Y");
Vector3 RotateX = new Vector3(CurX, 0f, 0f) * TurnSpeed;
var cam = Cam.transform.rotation;
transform.Rotate(RotateY);
Cam.transform.Rotate(-RotateX);
cam.x = Mathf.Clamp(cam.x, -AngleLimit, AngleLimit);
Answer by hrgchris · Feb 24, 2017 at 02:34 PM
You're hitting 2 problems:
you are reading the camera rotation (line 8), but not writing it back to the camera (line 12 just modifies the value you read)
even if you were reading/writing it, the 'rotation' value is a quaternion. I think you're probably thinking about the eulerAngles property as in the previous answer. However you'd still need to write it back.
I would try something like this:
Vector3 RotateX = new Vector3(CurX, 0f, 0f) * TurnSpeed;
transform.Rotate(RotateY);
Cam.transform.Rotate(-RotateX);
Vector3 cam_rotation = Cam.transform.eulerAngles;
cam_rotation.x = Mathf.Clamp(cam_rotation.x, -AngleLimit, AngleLimit);
Cam.transform.eulerAngles = cam_rotation;
As an extra note, simply clamping angles doesn't always yield the expected result, and I can't tell what that is from your code. However what I've provided above should certainly limit the value that the x component of the camera's eulerAngles property can take on.
I tried it and it did clamp it, but I couldn't even rotate on the x axis.
Then I would suggest you put in lots of Debug.Log calls throughout your code and print out the various variables involved.
I would start by printing out RotateX, cam_rotation (before/after changing it), TurnSpeed and AngleLimit. Presumably some of those numbers aren't changing how they should. When you find the one that's wrong, you've fixed your bug!
Answer by NGC6543 · Feb 24, 2017 at 08:31 AM
cam is in fact Quaternion. Probably what you intended to do was cam.eulerAngles.x
I put that in and I get an error saying its not a variable.
Your answer
Follow this Question
Related Questions
How to Math.f Clamp this 0 Answers
Bizzare problem with limiting camera veritcal rotation 2 Answers
Clamp horizontal rotation based on current direction 0 Answers
Clamping RotateAround 1 Answer
Rotating and orbiting an game object with a stop angle 0 Answers