Simple Player Movement in Unity

James Lafritz
4 min readMar 22, 2021

Set up the scene

In order to implement player movement we are going to need something in our scene to act as our player. Add a cube to the scene and name it Player. The scene should look similar to

Now Lets create a script for our player. In the project window add a folder called Scripts. In the Scripts folder add a C# script called Player.

Now add this script to the player by dragging the player script onto the Player in the hierarchy. If you view the Player in the Inspector window you should see the Player script has been added as a component.

Time to start coding

Move the player

To get the player to move we will need to use a method on the transform called Translate. Lets move the Player to the left at real time.

Add a speed variable

Lets add a speed variable that is only access from the player script but lets make sure that our game designers can change the speed in the inspector.

Lets add a tool tip so the designers know what changing this value will do.

Now lets Clamp this with a reasonable range.

Don’t forget to add the speed variable to the translate calculation.

User Input

Now lets use Unity’s Input System to control the player movement.

We will use the Horizontal for movement on the X axis and Vertical for movement on the Y axis.

Keeping the player in Bounds

Lets add some code to keep the player within a bounds set by the designer on the screen.

Next we set the Players position to start at the bounds center.

Now lets use the Unity event to draw this in the scene view when the game designer has the Player selected so they can see where the player will be bound to.

We are going to need a variable to keep track of the players position.

Lets clamp the player’s position to the bonds. In order to modify the transform position we first have to cache the Vector3 modify the individual components of the cache Vector3 and then set the transforms position to the cache Vector3

Instead of clamp the player on the x axis make the player wrap around the screen on the X axis.

Code Clean up

Add a variable to keep track of the direction to move the player.

Update the movement code

The Completed Class

--

--

James Lafritz

Excited about changing my hobby into a new carer with GameDevHQ course.