Why isn't this script working?

//I’m trying to make a script that will rotate an object when a key is pressed, but it doesn’t rotate backward. There are no compiler errors, and I don’t really know what I did wrong. any ideas? Here’s the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateOnKeypress : MonoBehaviour
{
    [SerializeField]
    KeyCode Left;
    [SerializeField]
    KeyCode Right;

    [SerializeField]
    KeyCode Up;
    [SerializeField]
    KeyCode Down;  

    void FixedUpdate()
    {
        //Left and Right
        if (Input.GetKey(Left))
            transform.Rotate(0, 1, 0);

        if (Input.GetKey(Right))
            transform.Rotate(0, -1, 0);

        //Up and Down
        if (Input.GetKey(Up) && transform.rotation.x < 91)
           transform.Rotate(1, 0, 0);

        else if (Input.GetKey(Down) && transform.rotation.x > 19)
            transform.Rotate(-1, 0, 0);
    }
}

Don’t use “transform.rotation.x” like that. You are thinking of Euler angles. Transform.rotation is a Quaternion. Its x, y, and z (and w) fields mean totally different things and do not directly correspond to pitch, yaw, or roll. You can’t rotate down because “transform.rotation.x” will never be greater than 19.

You could try doing the same thing but with “transform.eulerAngles.x”, and that might work. But you can’t really trust Euler angles to fall in any particular range, because

(a) Unity doesn’t explicitly store the Euler angles; the Quaternion is the “real” rotation, and if you ask for Euler angles then it converts the Quaternion into Euler angles on-the-fly

(b) The Euler angles to represent any given orientation are not unique; there are several different combinations of Euler angles that Unity theoretically could give you for any given rotation, and you might not get the one you’re expecting

The usual work-around (for angle-clamping based on player input) is to store the desired Euler angles yourself, in your own script, and always set the rotation to your saved angles, and never ask what angles the object is already at.

2 Likes

Thanks for the tips, dude! :smile: