- Home /
Mathf.Clamp is not clamping my minimum value
Mathf.Clamp is resetting my eulerangle to maxValue when it reaches the minValue instead of constraining it at minValue. My Script
rotate = Input.GetAxis("Mouse X") * senseX;
rotation = player.transform.eulerAngles;
rotation.y += rotate * RateOfRotate;
//while (rotation.y > 180)
// {
// rotation.y -= 360;
// }
rotation.y = Mathf.Clamp(rotation.y, lowLimitY, highLimitY);
player.transform.eulerAngles = rotation;
Here my lowLimmitY = 0 and highLimitY = 180 ; I am stuck at this and have no clue how to work around it. Any help will be appreciated.
I think it's because eulerAngles
switches to 359 when it goes to what should be -1. Could you check on that (Debug.Log the euler angle y value)? If so, you would do something like this:
if(rotation.y > 180) rotation.y = 360-rotation.y;
//insert before the clamp
Answer by JVene · Oct 30, 2018 at 02:56 AM
@Nomenokes is right, but I thought I'd expand on it a touch.
Clamp isn't actually appropriate for angles. What's required should be more accurately called a wrap, the way a clock face wraps from noon to 1 after touring from 2 through 11, or from 59 to 0 when referencing seconds or minutes. Angles can't be limited to a range of 0 to 180, as that would only be half the potential rotation. The extent of the range must be 360, for degrees (2 * PI for radians), but that could be from 0 to 359, wrapping to 0, or -180 to 180 (where wrapping is actually -179.999... to 179.999..., the fact is that -180 and 180 are the same if that is the range used.
Some input sources you may know only give you a partial rotation, and as such a wrap can be simple. However, a fully generalized wrap may have to contend with multiple rotations, resolving the result of multiple rotations into the correct range. I'll leave the latter for a search you can perform, but consider the case when your target rage is (in reality) -180 to 180, and you know only partial rotations will ever be applied (nothing approaching multiple rotations). In that case, something like this is appropriate:
if ( angle > 180 ) angle -= 360;
if ( angle <= -180) angle += 360;
Note the second version uses "less than or equal", which is optionally intended to ensure that -180 becomes 180 (which are the same thing, and thus there can't be two very different looking results that resolve to the same angle).