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.
Here is the basic guide on how to add player movement in Unity.
Create a new 3D project
Set up the scene or any object you want to represent your player character
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));}}
Lines 1–3: These lines make all the necessary imports.
Line 5: A class named PlayerMovement
is declared here which inherits from the MonoBehaviour
class. It provides basic player movement functionality.
Line 7: It declares a moveSpeed
variable which controls the speed at which the player moves.
Line 8: This line declares an object ch
with a CharacterController
component 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 by GetComponent
attached to the ch
object.
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 Horizontal
and Vertical
with appropriate input axes if you are using different input methods. The moveSpeed
is then multiplied by the Time.deltaTime
to ensure smooth movement of the player.
Line 19: Move
method is called on the ch
object to move the character. Adjust the axes if your game uses other coordinate system.
Select the player object
In the Inspector window, select Add Component
Search Character Controller
Press Add
Save all the changes
Select the player object
In the Inspector window, adjust the moveSpeed
of the player
Play the game
You should be able to move your player character around with the arrow keys.
Free Resources