0
votes

I want to rotate an object with the left arrow key and I want to bound the rotation to 30 deg. My code is:

if (Input.GetKey(KeyCode.LeftArrow) && transform.localEulerAngles.z <= 30)
   transform.Rotate(0,0,1);

Why rotation stops to 31 deg? Obviously my problem is more complex than this, I have different bounds and I need precision. The reason of this example is to simply say that rotations are not precise if managed in this way.

I think the reason is that Unity3D internally uses quaternions and acting on degrees is just an approximation. I'm right? In this last case how can I cope to this?

For example, how can I use quaternions to bound of 30 degs a rotation on an axis?

By the way if the problem is not this, do you have other solutions?

2

2 Answers

1
votes

I don't know how unity manage the rotation, but here your problem seem more simple.

In your if you use the '<=' comparison, so when your object is at 30 degree, you enter a last time in the if and rotate 1 more degree, use a '<' to stop at the right moment

0
votes

Get the current rotation in the Start() function then use it to find an offset that will be used to perform the if statement. This should do it:

public GameObject gameObjectToRotate;
Vector3 defaultAngle;
float minRot = 30f;
float maxRot = 30f;

// Use this for initialization
void Start()
{
    defaultAngle = gameObjectToRotate.transform.eulerAngles;
}

// Update is called once per frame
void Update()
{
    if (Input.GetKey(KeyCode.LeftArrow))
    {
        float offset = defaultAngle.z - gameObjectToRotate.transform.eulerAngles.z;
        //Check if we are within min, max rot
        if (offset < minRot && offset > -maxRot)
        {
            gameObjectToRotate.transform.Rotate(0, 0, 1);
            Debug.Log("Rotating!");
        }
    }
}

The precision is 30.016. This is much more better than what you are getting now.