- Home /
Clamping a Rotation
Hello Comm-Unity, I have been working on a game - as most are - and have hit a roadblock in my code. I'm trying to make a GameObject rotate depending on keys the user presses on the keyboard. Unfortunately, when I test it, the object just rotates past the cutoff angle. Here's my code:
void RotateObject()
{
/*Quaternion q = RotationObject.transform.rotation;
q.x = Mathf.Clamp (RotationObject.transform.rotation.x, RotationMin, RotationMax);
//q.y = Mathf.LerpAngle (q.y, this.transform.rotation.y, Time.deltaTime);
RotationObject.transform.rotation = q;*/
if(Input.GetKey(KeyCode.U))
{
LadderRotation.transform.Rotate(new Vector3(RotateSpeed * Time.deltaTime, 0.0f, 0.0f));
}
else if(Input.GetKey(KeyCode.J))
{
RotationObject.transform.Rotate(new Vector3(-RotateSpeed * Time.deltaTime, 0.0f, 0.0f));
}
Quaternion q = RotationObject.transform.rotation;
q.x = ClampAngle (q.x, RotationMin, RotationMax);
RotationObject.transform.rotation = q;
}
public static float ClampAngle (float angle, float min, float max)
{
if (angle == -360F)
angle += 360F;
if (angle == 360F)
angle -= 360F;
return Mathf.Clamp (angle, min, max);
}
Any help is much appreciated. Thank you, and have an awesome day!
Answer by mikelortega · Jan 04, 2017 at 11:13 AM
There are a couple of comments about your code.
Quaternion q.x is not an angle, it's a component of the rotation matrix, you want to compare with q.Euler.x
You should never compare floats with '=='. I think you want to compare (angle < -360.0f) and (angle > 360.0f)
Thanks mikelo! The answer really did the trick. To all future programmers who are looking at this, here's the modified code:
void RotateObject()
{
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.U))
{
RotationObject.transform.Rotate(new Vector3(RotateSpeed * Time.deltaTime, 0.0f, 0.0f));
}
else if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.J))
{
RotationObject.transform.Rotate(new Vector3(-RotateSpeed * Time.deltaTime, 0.0f, 0.0f));
}
Quaternion q = RotationObject.transform.rotation;
Vector3 v = q.eulerAngles;
v.x = ClampAngle (v.x, Rotation$$anonymous$$in, Rotation$$anonymous$$ax);
q.eulerAngles = v;
RotationObject.transform.rotation = q;
}
public static float ClampAngle (float angle, float $$anonymous$$, float max)
{
return $$anonymous$$athf.Clamp (angle, $$anonymous$$, max);
}
Once again, thank you mikelo!