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!

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)