Set up Player movement

Tutorial

·

Beginner

·

+10XP

·

30 mins

·

(59)

Unity Technologies

Set up Player movement

In this tutorial, you’ll add a movement script and physics systems to your character, allowing it to respond to input and move within the game.

1. Overview

In this tutorial, you'll implement player movement by creating a script that responds to user input. You'll also integrate Unity’s physics system to give your character realistic movement and interactions.

2. Add a Rigidbody component

To make the player character interact with Unity’s physics system, you need to add a Rigidbody component to the Player GameObject. This component allows the player character to respond to forces and collisions. Without a Rigidbody component, the player character wouldn’t be able to move realistically in the game world.

Additionally, to ensure the player character remains stable and moves only in the intended directions, you can freeze its movement along the Y-axis and restrict unwanted rotations. Unity uses a Y-up coordinate system, meaning the Y-axis represents vertical movement. By freezing Position Y, you can prevent the player character from floating or sinking. You’ll freeze Rotation X and Z to stop the player character from tilting sideways, ensuring it only rotates around the Y-axis to turn left or right.

1. Add a Rigidbody component to the player character:

  • In the Hierarchy window, select the Player GameObject.
  • In the Inspector window, select the Add Component button.
  • Search for “Rigidbody” (not Rigidbody 2D) and select it.

Note: To work more comfortably through this tutorial, consider disabling your Scene gizmos. You can do this by clicking the Toggle visibility of all Gizmos in the Scene view button on the rightmost side of the toolbar at the top of the Scene window

2. Test the Rigidbody component:

  • Select the Play button in the Unity Editor.
  • Observe that the player character falls through the ground due to gravity.

3. Apply movement constraints:

  • In the Inspector window, use the foldout (triangle) to expand the Constraints section of the Rigidbody component.
  • Enable Freeze Position Y to prevent the player character from moving vertically.
  • Enable Freeze Rotation X and Freeze Rotation Z to keep the player character from tilting sideways.

4. Test again to confirm constraints:

  • Select the Play button and ensure that the player character no longer falls through the ground and remains upright.
  • If needed, use Ctrl+Z (macOS: Cmd+Z) to undo mistakes.

The Rigidbody component is now applied to the player character, allowing it to interact with Unity’s physics system while ensuring that it remains stable and moves only in the intended directions.

3. Add a collider component

Right now, the player character could move through buildings and other GameObjects because it lacks a collider component. A collider component defines a GameObject’s physical boundaries, allowing it to interact properly with the environment. In this step, you'll add a Capsule Collider component to the Player GameObject and adjust its shape for accurate collisions.

1. Add a Capsule Collider component to the Player GameObject:

  • Select the Player GameObject.
  • In the Inspector window, select the Add Component button.
  • Search for and add the Capsule Collider component.
  • A faint green capsule will appear around the Player GameObject, representing the Capsule Collider component.

2. Adjust the collider to fit the player:

  • In the Inspector window, in the Capsule Collider component, select the Edit Collider button.
  • Drag the collider handles to resize and reshape the capsule.

Important: Ensure that the Capsule Collider component covers all of the character’s body, feet and face but not its arms.

3. Improve accuracy with different view angles:

  • The collider might not actually be perfectly aligned, even if it looks good from one angle.
  • Use the Scene gizmo to rotate the view.
  • Switch to Orthographic view for more precise adjustments:
    • Select the Scene gizmo and select a side, top, or front view.
    • This makes it easier to see if the collider fits the player character’s shape correctly.
  • Right-click the Scene gizmo and select Free mode to return to a more natural viewing angle.

The player character now has a collision boundary, preventing it from moving through other GameObjects in the scene.

4. Create the PlayerMovement script

In Unity, you define how your GameObjects behave using code. For example, to control how a character moves when you press certain keys—just like in most video games—you'll need to create a script that tells the player character exactly what to do and when.

To make things easier, we've provided the complete script for you. If you're new to coding, this means you can keep moving forward with your project without getting stuck.

If you're curious to understand how the script works, check out Step 7, where we explain the key parts in more detail. If you already have some experience, you’re welcome to write your own version of the PlayerMovement script and customize it as you like!

1. Create a new script:

  • In the Project window, right-click the _3DStealthGame folder and select Create > Folder.
  • Rename the new folder “Scripts”.
  • Right-click the Scripts folder and select Create > MonoBehaviour Script.
  • Rename the script “PlayerMovement” and press Enter.

2. Open the script:

  • Double-click the newly created PlayerMovement script.
  • This will open the script in the code editor or integrated development environment (IDE) you've set up (such as Visual Studio).

Important: If the code doesn't open in your IDE, follow these instructions to install modules for your Unity version.

3. Copy the provided code:

  • Once the script is open, delete any pre-filled content.
  • Paste in the following code, and then save your script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
    public InputAction MoveAction;

    public float walkSpeed = 1.0f;
    public float turnSpeed = 20f;

    Rigidbody m_Rigidbody;
    Vector3 m_Movement;
    Quaternion m_Rotation = Quaternion.identity;

    void Start ()
    {
        m_Rigidbody = GetComponent<Rigidbody> ();
        MoveAction.Enable();
    }

    void FixedUpdate ()
    {
        var pos = MoveAction.ReadValue<Vector2>();
        
        float horizontal = pos.x;
        float vertical = pos.y;
        
        m_Movement.Set(horizontal, 0f, vertical);
        m_Movement.Normalize ();

        Vector3 desiredForward = Vector3.RotateTowards (transform.forward, m_Movement, turnSpeed * Time.deltaTime, 0f);
        m_Rotation = Quaternion.LookRotation (desiredForward);
        
        m_Rigidbody.MoveRotation (m_Rotation);
        m_Rigidbody.MovePosition (m_Rigidbody.position + m_Movement * walkSpeed * Time.deltaTime);
    }
}

4. Add the script to your Player GameObject:

  • In the Hierarchy window, select the Player GameObject.
  • In the Inspector window, select the Add Component button.
  • Search for and add the PlayerMovement component.

You’ve successfully created a new script that will control your player character’s movement and attached it as a component.

5. Assign the Player Movement variables

In Unity, scripts work just like any other component you add to a GameObject to give it new functionality. They can have properties or variables that define things like speed, intensity, or other aspects of the script's behavior. In this step, you'll assign values to the variables in the script you just created and test how your Player GameObject behaves with it.

1. Review the public variables:

  • You can see there are two variables you can change directly in the Editor:
    • Walk Speed: Controls how fast the player character moves forward or backward.
    • Turn Speed: Controls how quickly the player character rotates left or right.

2. Assign the Move Actions:

  • In the Move Action section, select the (+) button.
  • Select Add Up/Down/Left/Right Composite. Rename the composite “WASD”.
  • Double click the Up <No Binding>, select Path > Listen, press the W key, then select W [Keyboard].
  • Repeat the same process to assign the following bindings:
    • Down <No Binding> > S [Keyboard]
    • Left <No Binding> > A [Keyboard]
    • Right <No Binding> > D [Keyboard]

Note: To support arrow keys too, you can add another Up/Down/Left/Right Composite, rename it “Arrow” and assign the up/down/left/right arrow keys accordingly.

3. Test the movement in Play mode:

  • Select the Play button at the top of the Unity Editor.
  • Use the WASD keys or Arrow keys to move the player character.
  • Try adjusting the Speed and Turn Speed values during Play mode to experiment with different movement styles.

Note: The movement is global, so pressing the up key will always move the player upward on the world axis, not relative to the character’s current facing direction.

4. Exit Play mode:

  • Exit Play mode before making further modifications.

Note: Any changes you make to the variables while in Play mode will be lost when you exit it. If you find a combination you like, make sure to write down the values and reapply them after exiting Play mode.

Your Player GameObject now has the PlayerMovement component correctly assigned and responds to keyboard input just like a real game character.

6. Create a prefab of your Player GameObject

Converting your Player GameObject into a prefab allows you to reuse it easily. Any changes made to the prefab will update all instances in your game.

1. Create a new folder:

  • In the Project window, navigate to _3DStealthGame > Prefabs.
  • Right-click the Prefabs folder, select Create > Folder, and name it “Characters”.

2. Convert the Player GameObject into a prefab:

  • Select the Player GameObject in the Hierarchy window.
  • Drag it into the Characters folder in the Project window.

Check that the Player GameObject in the Hierarchy window now has a blue cube icon, indicating it is a prefab instance.

Note: Now that the tutorial is complete, remember to re-enable the gizmos that were disabled earlier. To do this, click again the Toggle visibility of all Gizmos in the Scene view button on the rightmost side of the toolbar at the top of the Scene window.

3. Save your scene:

  • Press Ctrl+S (macOS: Cmd+S).

Your Player GameObject is now a prefab, allowing you to create multiple copies of it while keeping them linked.

7. Review the PlayerMovement script

This step is entirely optional, but if you’re curious to understand how the PlayerMovement script works, below are a few aspects of the script that you might find particularly interesting.

1. Calculate movement in the FixedUpdate Method:

FixedUpdate() is a special Unity’s method that runs at a consistent rate and is ideal for applying movement or forces.

void FixedUpdate ()
    {
        var pos = MoveAction.ReadValue<Vector2>();
        
        float horizontal = pos.x;
        float vertical = pos.y;
        
        m_Movement.Set(horizontal, 0f, vertical);
        m_Movement.Normalize ();
        .
        .
        .
  • MoveAction.ReadValue<Vector2>() gets the current movement input from the Player GameObject.
  • horizontal and vertical represent input along the X and Z axes (left/right and forward/back).
  • m_Movement.Set() creates a 3D vector from the 2D input (with Y set to 0).

2. Apply Movement Direction and Rotation:

After you calculate the movement direction based on user inputs, you need to tell Unity to use it.

Vector3 desiredForward = Vector3.RotateTowards (transform.forward, m_Movement, turnSpeed * Time.deltaTime, 0f);

m_Rotation = Quaternion.LookRotation (desiredForward);
        
m_Rigidbody.MoveRotation (m_Rotation);

m_Rigidbody.MovePosition (m_Rigidbody.position + m_Movement * walkSpeed * Time.deltaTime);
  • desiredForward stores a Vector3 that represents the smoothly adjusted forward direction, transitioning from the Player GameObject's current facing direction (transform.forward) toward the target movement direction (m_Movement).
  • m_Rotation then stores the actual rotation that the Player GameObject needs to adopt in order to face desiredForward.
  • MoveRotation(m_Rotation) applies this smooth rotation to the Rigidbody component, making the Player GameObject rotate physically toward the intended direction.
  • MovePosition() moves the Rigidbody component forward in the m_Movement direction, using the defined walkSpeed, ensuring the Player GameObject actually walks in the direction they’re facing.

If you’d like to dive deeper into programming, we recommend checking out the Junior Programmer Pathway, where you’ll learn the fundamentals of coding in Unity.

8. Next steps

With these steps completed, your Player GameObject now has a responsive movement script that allows the user to move the character based on their input.

In the next tutorial, you’ll add animations to your player character.

Complete this tutorial