Hi all,
I’m having a problem clamping a rotation between two points on the Z axis. If, for example, I clamp between 10 and 350 degrees, the Mathf.Clamp function assumes I want to exclude the 20 degrees between 10 and 350.
But what I want to do is clamp within the 20 degrees separating the two angles. In other words, I want to clamp within the shortest distance, not the longest between two angles. I’m having trouble figuring out the simplest way to do this. Should be easy, but it’s got me baffled.
Can you Mathf.Clamp( -10, 10 )? It’s worth a shot.
If that doesn’t work, you’ll need to manually clamp it - if ( > 10 < 180 ) angle = 10, etc
Thanks for that. I used your second method ( with the statement) and it works perfectly.
if (transform.eulerAngles.z >65 transform.eulerAngles.z<180) transform.eulerAngles.z = 65;
else if (transform.eulerAngles.z<295 transform.eulerAngles.z>180) transform.eulerAngles.z = 295;
I’ve seen a number of posts that ask more or less the same question with regard to turrets etc. As a suggestion to the Unity team, it might be useful to have a clamp function for angles in which you can select a central point and clamp a certain number of degrees on either side of that point, regardless of where it is in the 360 degrees of the circle, and perhaps a third parameter to indicate whether it’s in world or local space. Might look something like this:
ClampAngle (290, 30, Space.World) where 290 would be the central point and it would clamp between 260 and 320 degrees.
Seems like it might save time for a lot of people. Just a thought.