Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Rotation on input question

Discussion in 'Scripting' started by Jhoffy, Aug 15, 2016.

  1. Jhoffy

    Jhoffy

    Joined:
    Aug 14, 2016
    Posts:
    4
    Hello everyone. Im working on a script where a cube would rotate 90 degrees, at a set speed, whenever a key is pressed. The current code im working with is:

    float rotationAmount = 1f;
    // Use this for initialization
    void Start()
    {
    }
    // Update is called once per frame
    void Update()
    {
    if (Input.GetKey(KeyCode.A))
    {
    if (transform.rotation.eulerAngles.y >= 89 && transform.rotation.eulerAngles.y <= 91)
    {
    while (transform.rotation.eulerAngles.y <= 180)
    { transform.Rotate(0, rotationAmount * Time.deltaTime, 0); }

    Then would put else ifs for the other degrees (0, 90, 180, 270). Currently when I press A it snaps 90 degrees instead of rotating the 90 at a slower rate. I have lowered and played with my variable of rotationAmount to no avail. Is there something I am missing? Or is there a better way to do this?
    Thanks in advance
     
  2. traderain

    traderain

    Joined:
    Jul 7, 2014
    Posts:
    108
    Code (CSharp):
    1. float rotationAmount = 1f;
    2. // Use this for initialization
    3. void Start()
    4. {
    5. }
    6. // Update is called once per frame
    7. void Update()
    8. {
    9. if (Input.GetKey(KeyCode.A))
    10. {
    11. if (transform.rotation.eulerAngles.y >= 89 && transform.rotation.eulerAngles.y <= 91)
    12. {
    13. while (transform.rotation.eulerAngles.y <= 180)
    14. { transform.Rotate(0, rotationAmount * Time.deltaTime, 0); }
    Use code tags please ty. Anyway I would say get the gameobject than divide 90 by the speed than change to quaternion of the gameobject or you can also lerp to make it smoother(check the documentation). Good luck.