How do I limit rotations for both positive and negative degrees?
So what I'm trying to do is limit an objects rotation, however, when the object reaches a negative rotation, it snaps to 60 just like it would with a rotation above 60 degrees (my code explains it)
For example whenever the rotation reaches -1 degrees , it snaps to 60 degrees, is there any way to fix this?
(I also thought about the fact that maybe -1 degrees is being detected as 359 degrees, but I'm not sure about that.)
float currentZ = transform.localRotation.eulerAngles.z;
if (currentZ > 60) {
currentZ = 60;
transform.localEulerAngles = new Vector3 (transform.localRotation.eulerAngles.x, transform.localRotation.eulerAngles.y, currentZ);
}
EDIT:
I figured it out myself, the rotation DOES become 359, so for that reason all I had to do was instead of making it check if currentZ > 60, making it check if currentZ > 60 && currentZ < 180. And of course for the negative rotations make it if currentZ < 300 && currentZ > 180.
I'm just gonna leave this up here for other people with the same question or for suggestions that would work better than my code.
Answer by AurimasBlazulionis · Dec 16, 2016 at 06:05 PM
You should use something like this: currentZ = Mathf.ClampAngle(currentZ, -60, 60)
. The basic if/else statements will not work, because of how unity handles rotation internally.
Your answer
![](https://koobas.hobune.stream/wayback/20220612102805im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to get rotation degrees? 1 Answer
Help! I can't get this code to function correctly 1 Answer
problem setting rotation 1 Answer
Smooth rotation on Y axis to target pose 0 Answers
Smooth cube rotation exactly 90 degrees 2 Answers