Search code examples
unity-game-engineinputrotationtransformquaternions

manually change a rotation in unity


So here is my problem : I have an object in Unity that is my Player. I want this Player to be able to face the direction where he is moving. but I don't know how to rotate an object until the specific key is released and then repositioning the rotation to 0,0,0

i tried this code

public class PlayerAction : MonoBehaviour
{
public float horizontalInput;
public float verticalInput;
// Start is called before the first frame update
void Start()

    
}

// Update is called once per frame
void Update()
  {
    horizontalInput = Input.GetAxis("Horizontal");
    verticalInput = Input.GetAxis("Vertical");

    if (horizontalInput > 0)
    {
        transform.Rotate(0, 90, 0);
    }
  }
}

And I was looking on Quaternion but didn't understand anything on any forum.

To clarify I want to manually change the rotation of the Player


Solution

  • Find this example where you can rotate around y axis to each of the sides and reset back to the original rotation respectively.

    using UnityEngine;
    
    public class Rotation : MonoBehaviour {
        private Quaternion startingRot;
    
        void Start() {
            startingRot = transform.rotation;
            }
    
        void Update() {
    
            if (Input.GetKeyDown(KeyCode.P)) {
                transform.Rotate(0, 45, 0);
            }
    
            if (Input.GetKeyDown(KeyCode.O)) {
                transform.Rotate(0, -45, 0);
            }
    
            if (Input.GetKeyUp(KeyCode.L)) {
                transform.rotation = startingRot;
            }
        }
    }
    

    Quaternions are a mathematical tool to handle rotations. They are far less intuitive than eulerAngles, but are much more efficient computationally and address a know issue with the eulerAngles, the Gimbal lock.

    You dont need to worry about this for the moment but just for your info:

    Unity provides the way to interact with rotations with euler angles in the code the same as as in the editor, but the rotatations are dealt with quaternions. That is why many times you will find some unexpected values in the unity's editor transform rotation window, because unity is permanently translating from the quaterninons it handles internally to the euler angles shown in the editor user interface.