So I’ve been racking my brains for the past couple of days trying to figure out a rotation problem I’ve been getting.
Basically I’ve set my cube up to rotate right 90 degrees by detecting when its at 90 degrees x rotation which works fine. But when I rotate it back to 0, it fails to detect when the angle is at 0 and thus fails to stop.
void LateUpdate()
{
if(rightKeyPressed == true)
{
//Rotate around the v3Pos, which is a pivot point
transform.RotateAround(v3Pos, transform.right, Time.deltaTime * cubeSpeed);
//Stops at 90 degrees, detects fine
if(xAngle == 90)
{
transform.RotateAround(v3Pos, -transform.right, Time.deltaTime * cubeSpeed);
print ("xAngle = 90.0");
}
} else if(leftKeyPressed == true)
{
//Rotate back to 0 degrees, works fine
transform.RotateAround(v3Pos, -transform.right, Time.deltaTime * cubeSpeed);
//Fails to detect
if(xAngle == 0.0)
{
transform.RotateAround(v3Pos, transform.right, Time.deltaTime * cubeSpeed);
print ("xAngle = 0.0");
}
}
}
That’s what I though. I’m surprised the “if (xAngle == 90)” part works. The first issue you have is there is no guarantee that the angle will hit any target given you are using deltaTime. That is the angle could go from 89.999 to 90.0001 never hitting 90. The second issue is the direct comparison of floating numbers. Even when a calculation should turn out even number, you may in fact have something like 0.00000000000000000000001, and the code “x == 0” will fail. And then you have the issue of the 0/360 boundary to deal with. Plus, if you do other rotations with your game object, there is no guarantee that a 45 degree rotation about the X-axis will be represented by a euler value of 45 (i.e. the same rotation can often be represented my multiple different euler settings).
Here is an attempt at a “fix” for your code. It still suffers from the issue that if you have other rotations going on, a 90 X axis rotation might not be euler 90, and therefore this code can fail.
public class RotateUpDown : MonoBehaviour {
public float cubeSpeed = 22.0f;
void Update() {
float xAngle = transform.eulerAngles.x;
if (xAngle > 180.0f) // Normalize the angle to -180 to 180
xAngle -= 360.0f;
if(Input.GetKey (KeyCode.UpArrow)) {
if (xAngle < 90.0f)
transform.RotateAround(transform.position, transform.right, Time.deltaTime * cubeSpeed);
} else if(Input.GetKey (KeyCode.DownArrow)) {
if (xAngle > 0.0f)
transform.RotateAround(transform.position, -transform.right, Time.deltaTime * cubeSpeed);
}
}
}