- Home /
Clamping Camera doesn't work
I'm trying to clamp my camera's rotation on the x axis, but when it goes down to 0, it snaps back to 45. Here is the portion of the script that clamps the camera. Here is the script:
Vector3 rot = transform.eulerAngles;
rot.z = 0;
if (rot.x > 45f) {
rot.x = 45f;
}
if (rot.x < -45f) {
rot.x = -45f;
}
transform.eulerAngles = rot;
I also tried switching -45f to 315f, (which I knew wouldn't work) and it just glitched the camera a bunch.
Answer by PatriceVignola · Aug 01, 2015 at 07:33 AM
This behavior happens because, no matter what, the value of transform.eulerAngles.x
will never be negative when you get it from the scene since the engine works with floats from 0 to 360 when it comes to angles (so your -45 becomes 315). Even when you manually assign a vector with negative components to it, it's gonna get converted back to the [0, 359[ before the next frame.
Your reflex of trying with 315 was half the solution, but you also have to manually check if the angle is over 180 (negative) or under 180 (positive), since values from 0 to 45 are also smaller than 315.
The following changes to your code snippet should solve your problem:
Vector3 rot = transform.eulerAngles;
rot.z = 0;
if (rot.x > 45f && rot.x < 180f){
rot.x = 45f;
}
else if (rot.x > 180f && rot.x < 315f){
rot.x = -45f;
}
transform.eulerAngles = rot;
Your answer
Follow this Question
Related Questions
Confining Mouse Look on X axis 0 Answers
3rd person camera not smooth 1 Answer
Enable a component after a specific amount of time? 4 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers