Search code examples
c#unity-game-enginerotationgame-physicspath-finding

Smooth character rotation


Here is my code for moving in the four cardinal directions:

    if (Input.GetKeyDown(KeyCode.RightArrow)){
        transform.forward = new Vector3(0f, 0f, 1f);
        }
    else if (Input.GetKeyDown(KeyCode.LeftArrow)){
        transform.forward = new Vector3(0f, 0f, -1f);
        }
    else if (Input.GetKeyDown(KeyCode.DownArrow)){
        transform.forward = new Vector3(1f, 0f, 0f);
        }
    else if (Input.GetKeyDown(KeyCode.UpArrow)){
        transform.forward = new Vector3(-1f, 0f, 0f);
        }

My character instantly rotates in the four directions of travel The problem I'm having is trying to figure out how I can smooth out inbetween directions. What I'm trying to say is, if the character is pointing north and you push the button to go west, instead of instantly turning west, I would like to see the character rotate smoothly in degrees to the westward direction.

Ive search and tried tutorials, but none of them worked. Any solution?


Solution

  • Take a look at the Slerp function. This will probably do what you want.

    http://unity3d.com/support/documentation/ScriptReference/Quaternion.Slerp.html

    Simple example:

        newdir.y=-135; // depends on which axis you want to turn...
    
    transform.rotation = Quaternion.Lerp(transform.rotation, newdir, Time.deltaTime * smoothSpeed);
    

    So you basically get the Quaternion of your current rotation. Copy that in a new Quaternion and increase or decrease the the rotation on one or more axis.