Simple player movement in Unity
In this article you’ll learn about adding simple player movement to the GameObject, adding a toggle to swap between restricting or wrapping player bounds and as a little extra to apply a boost to our player.
Before we add the logic for the player to move, let’s open up a new script in Unity.
Add a Cube to your scene and make sure you have selected it. Hit the “Component” button in the inspector and add a new script called “Player”. When you open the script it will look like this by default.
The script is populated with two functions, Start and Update.
The Start function will get called once when the object to which the script is attached has loaded in the scene.
In the Update function, any code will get called once per frame.
In the Update function, we want to avoid having our actual logic for the code since it is called once per frame. To keep it well organised and prevent messy code clusters, make a habit of calling other functions inside the Update function.
Let’s add some simple player movement logic to our code.
We start by storing our GameObject’s new transform position inside a struct called Vector3 where Vector3 stands for three positions x, y and z.
We multiply that with a variable called _speed to set the speed at which the player is moving.
Because the Update() function is frame dependent, frames per second will vary between hardware so we need to return an average of frames for all devices. We do that by multiplying our input with Time.deltaTime.
New Position = Player Location + Directional Input * Speed * Equal frame return
Update New Position to Object’s Transform
In the Start() function we set our transform position to 0 on all axes so that when the game starts the transform.position is reset to 0.
The variable in which we store the player speed, should be set to private instead of public since we don’t want anyone to mess with the input logic. However, we’d like to set it as visible in the inspector for fellow developers. Therefore we add a [SerializeField] to the variable.
Before we store our new position to our GameObject, let’s add some logic with an if statement to make the player wrap around the screen when the camera view bounds are reached.
Let’s also add an option to restrict our player movement to the camera view bounds. We’ll use a function called Mathf.Clamp to clamp a variable between two values. To toggle between wrapping we add a custom function called ToggleWrap().
As a little extra we can add a private _boost variable to our script and create a local variable inside the PlayerMovement() function called currentSpeed. Instead of multiplying our new position only with _speed, the code is now checking if Left Shift is held in order to apply a boost to currentSpeed.
In the end your script should look like the following: