Pointing in the Direction of Movement - Unity Game Development Tutorial

In this Unity game development tutorial we'll look at how we can rotate an object so that it is facing in the direction it is moving.

1. To get started let's create a new 3D project in Unity Hub.

Creating a new 3D project in Unity Hub

2. Add a Plane to the scene to represent our floor by clicking the plus button on the Hierarchy panel and selecting 3D Object->Plane.

Adding a plane in hierarchy panel

3. We'll use a capsule to represent our player. Add this to the scene by clicking the plus button on the Hierarchy panel and selecting 3D Object->Capsule.


4. Set the position of the capsule to (0, 1, 0) in the Inspector panel to position it on top of the plane.

Setting the position of the capsule

5. Right click on the capsule and click 3D Object->Capsule. This will create another capsule that is attached to the original one. 

Creating a capsule attached to the original

6. We'll use this to show which way we are facing. To do this set the following transformations on the  the new capsule.

Setting the transform of the attached capsule

You should now have a capsule with a smaller one protruding.

Capsule with another protruding

7. The next thing we need is a script to contain our logic. To do this, select the original capsule in the Hierarchy, click on the 'Add Component' button in the Inspector panel, search for script and click 'New Script'. Call the new script PlayerMovement.

Creating a new scrpt

8. Double click the PlayerMovement script in the Project panel to open the script in Visual Studio. You'll see the default script which has a method called Start and another called Update. 

The Start method is called when the Scene starts. We won't be needing this for this script so it can be deleted.

The update method is called every frame and this is where we'll be putting our logic.

Change the script to match the following.

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed;

    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        Vector3 movementDirection = new Vector3(horizontal, 0, vertical);
        movementDirection.Normalize();

        transform.position += movementDirection * speed * Time.deltaTime;
    }
}

This script processes player input from the keyboard or gamepad and uses it to move the capsule in the corresponding direction. If you find any of this unfamiliar I suggest looking at our tutorial on movement.

9. Save the script and switch back to Unity. As we created a public variable for the speed it is available to set in the Inspector panel. Set the value to 5.

Setting the speed variable

10. Switch to the Game view and press the play button. If you now press the arrow keys, the WASD keys or use the left thumbstick of a connected gamepad, you will see the capsule moving in response. 

11. The capsule is moving but it is not yet turning to face the direction it is moving. To fix this, switch back to the script and add the highlighted lines.

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed;

    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        Vector3 movementDirection = new Vector3(horizontal, 0, vertical);
        movementDirection.Normalize();

        transform.position += movementDirection * speed * Time.deltaTime;

        if (movementDirection != Vector3.zero)
        {
            transform.forward = movementDirection;
        }
}
}

First of all, we are checking if the capsule is moving by checking that the movementDirection is not zero. If it is moving we are then setting the forward direction to the movementDirection.

12 Save the script and return to Unity. Switch to the Game view and press the play button. If you move the capsule again the protruding capsule will now point in the direction of the movement.

Capsule pointing in the direction of movement

13. While this does what we set out to achieve, the instant rotation can be a little jarring. We can make the rotation much smother by making the following changes to the script.

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float speed;    
    public float rotationAnglePerSecond;
void Update() { float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); Vector3 movementDirection = new Vector3(horizontal, 0, vertical); movementDirection.Normalize(); transform.position += movementDirection * speed * Time.deltaTime;

        if (movementDirection != Vector3.zero)
        {
          Quaternion fromRotation = transform.rotation;
Quaternion toRotation = Quaternion.LookRotation(movementDirection, Vector3.up); transform.rotation = Quaternion.RotateTowards(fromRotation, toRotation, rotationAnglePerSecond * Time.deltaTime);
        }
}
}

This new code will make the capsule rotate toward the movement direction at a specific rate. First of all we have added a public variable so that the rate of rotation can be set from the Inspector in Unity. Within the if block we then get the from and the to rotation. The from rotation is the current rotation of the capsule. The to rotation is calculated by using Quaternion.LookRotation, passing in the direction we want to look at, which is the movement direction, and the up direction. We then use Quaternion.RotateTowards to rotate towards the desired direction at the rate specified in the rotationRatePerSecond variable. Remember we need to multiply the rotation rate by Time.deltaTime to ensure the capsule rotates at the same speed regardless of our framerate.

14. Save the script and switch back to Unity. As we created a public variable for the rotation angle it is available to set in the Inspector panel. Set the value to 360.

Setting the rotation angle

15. Switch to the Game view and press the play button. If you move the capsule now the rotation will be much smoother.

That covers everything for this tutorial. We hope you found it useful. Please leave any questions or feedback in the comments below, and don't forget to subscribe to get notified when we publish our next post.

Thanks.

Comments

Popular posts from this blog

Rotating a Character in the Direction of Movement - Unity Game Development Tutorial

Changing the Colour of a Material - Unity Game Development Tutorial

Creating Terrain from Heightmaps - Unity Game Development Tutorial