Rotation is starting at 0, how do I use Math.Clamp() on it?
I have a plane that I'm rotating with the arrow keys along the x and z axis'. The rotation starts at 0, so when I try to limit rotation with aMathf.Clamp()`, like Mathf.Clamp(clampedRotation.x, -20, 20)
, it works in one direction but not the other because it leaps from 360 to 20.
Are there other properties I can use a negative number? Or some concept I'm missing? I can't figure out how to get this right using positive numbers (but I'm no genius when it comes to the math, either). Thanks!
Comment
Answer by wachief · Sep 11, 2016 at 09:10 AM
hi, i hope this will help
//the vlaues you want to clamp to
float maxValueX=20;
float minValueX=-20;
//example for the x axis
// make a quaternion with only the x rotation
Quaternion xRotation = Quaternion.Euler(transform.eulerAngles.x, 0, 0);
//get the angle from the state of no rotation - will give you the change form 0 in positive angles
float angle = Quaternion.Angle(Quaternion.identity, xRotation);
float fixedAngle = angle;
//if the euler angle x is greater than 180 your angle should be a minus
if (xRotation.eulerAngles.x>180)
{
fixedAngle *= -1;
}
float clampedX = Mathf.Clamp(fixedAngle, minValueX, maxValueX);
Quaternion fixedRotationX = Quaternion.Euler(clampedX, 0, 0);
//set the fixed Rotation
transform.rotation = fixedRotationX;