- Home /
Clamping between everything but the min/max values
I have an object, and i want to clamp the z value between -90, and 90. So it has a total of 180 degrees it can go. This is my problem, when in play mode, it is no longer -90, and it is 270. So i need to clamp my angle from 90, to 270, mathematically this is from 90 to 270, but i want it to include 0 to 90, and 270 to 360 its hard to explain so i made a picture right here : http://puu.sh/iB8Lo/f18dede505.png
here is my code in case i'm doing something wrong
Quaternion clamp = Quaternion.Euler(transform.localEulerAngles.x, transform.localEulerAngles.y, Mathf.Clamp(transform.localEulerAngles.z, -90, 90));
transform.rotation = clamp;
Well, something like this might work. This should make your z angle always between -180 and 180 before clamping.
Quaternion clamp = transform.localEulerAngles;
while (clamp.z >= 180f)
clamp.z -= 360f;
while (clamp.z < -180f)
clamp.z += 360f;
clamp.z = $$anonymous$$athf.Clamp(clamp.z, -90, 90);
transform.rotation = clamp;
Answer by Dave-Carlile · Jun 24, 2015 at 04:59 PM
Haven't tested this, but it might/should work? The basic idea is that if z
float z = transform.localEulerAngles.z;
z = Mathf.Clamp((z <= 180) ? z : -(360 - z), -90, 90);
This works, i feel bad because i just pasted it in to my code and it just works, so thank you very much. But i'm pretty new to coding and haven't seen all the ? and : things. Is it like a compact if statement? $$anonymous$$abye link me to where i could read about this?
It's called the ternary operator or conditional operator. It's more or less the same as writing...
... if (z
But it's nice sometimes to be able to do it inline ins$$anonymous$$d of a separate if
statement.
I am not sure if i am late to respond to this. the code is working fine and thanks for this. the only question i have is if the angles are from 0-360 how come its working with -45 to 45.
Your answer
![](https://koobas.hobune.stream/wayback/20220613201344im_/https://answers.unity.com/themes/thub/images/avi.jpg)