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. Dismiss Notice

Smooth rotation upon button hold press and back

Discussion in 'Scripting' started by Hungry-Lion, Nov 4, 2018.

  1. Hungry-Lion

    Hungry-Lion

    Joined:
    Sep 2, 2018
    Posts:
    21
    Hello everyone, here is what I want to do:

    So I want to rotate the object towards target as long as a key is held down but upon releasing the key I want the object to start rotating back to its original direction and facing.

    What I did so far:
    void Update () {
    movement ();
    if (Input.GetButton("Fire1")) {
    shoot ();

    }

    if (Input.GetKey (KeyCode.Q)) {
    uTurn ();
    }
    //Thruster


    }

    private void uTurn(){

    //Turn left
    Quaternion newRotation = Quaternion.AngleAxis(180, Vector3.up);
    GetComponent<Rigidbody> ().rotation = Quaternion.Lerp (transform.rotation, newRotation, Time.deltaTime * 5f);
    }


    I get it to turn to where I want it smoothly when I held a key down but when I release the key it just snaps back to the default like faster than lightspeed or something.
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    please use code tags, makes it much easier to read
    Code (CSharp):
    1. if(pressing button)
    2. Lerp (transform.rotation, newRotation)
    3. else
    4. Lerp (transform.rotation, oldRotation)
     
  3. Hungry-Lion

    Hungry-Lion

    Joined:
    Sep 2, 2018
    Posts:
    21
    Thanks a lot @SparrowsNest I acted upon your example and solved it!
    And sorry, I will do as you say next time
     
  4. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    another thing that flew by me, when using rotations you'll want to use Slerp instead of Lerp.