How to add player movement in Unity
Adding player movement is crucial for dynamic experiences and interactive game designs. It is the primary method to engage users with the game world, interact with game characters or objects, and explore game environments.
Without movement, a game could limit the player's sense of immersion and make it feel static. Therefore, understanding and implementing player movement is essential in game development.
How to add movement
Here is the basic guide on how to add player movement in Unity.
Set up up the scene
Create a new 3D project
Set up the scene or any object you want to represent your player character
Create a player controller script
Select the player character
In the Inspector window, select Add Component
Name the script and press Create
Here is the sample C# script to enable movements of the player.
using System.Collections;using System.Collections.Generic;using UnityEngine;public class PlayerMovement : MonoBehaviour{public float moveSpeed;private CharacterController ch;void Start(){ch = GetComponent<CharacterController>();}void Update(){float x = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;float z = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;ch.Move(new Vector3(x, 0, z));}}
Explanation
Lines 1–3: These lines make all the necessary imports.
Line 5: A class named
PlayerMovementis declared here which inherits from theMonoBehaviourclass. It provides basic player movement functionality.Line 7: It declares a
moveSpeedvariable which controls the speed at which the player moves.Line 8: This line declares an object
chwith aCharacterControllercomponent attached to it. It allows easy character movement.Lines 10–13:
Start()method is called only once when the play button is clicked. It gets the controller component byGetComponentattached to thechobject.Line 15:
Update()function is called once per frame every frame.Lines 17–18: These lines get input from the player which can be controlled by the keys. You can replace the
HorizontalandVerticalwith appropriate input axes if you are using different input methods. ThemoveSpeedis then multiplied by theTime.deltaTimeto ensure smooth movement of the player.Line 19:
Movemethod is called on thechobject to move the character. Adjust the axes if your game uses other coordinate system.
Add Character Controller
Select the player object
In the Inspector window, select Add Component
Search Character Controller
Press Add
Tune and Test
Save all the changes
Select the player object
In the Inspector window, adjust the
moveSpeedof the playerPlay the game
You should be able to move your player character around with the arrow keys.
Demonstration
Free Resources