Simple player movement for a 2D game in Unity, C#

Alberto Garcia
3 min readNov 16, 2022

--

This article will mainly explore one function to simply implement player movement using the arrows or “wasd”. For simplicity let’s call this function CalculateMovement().

Before writing the function, let’s set up the player with a speed variable, an Awake() position, and a reference to the function we are creating.

Player set up at origin “(0, 0, 0)”

Serializing the private variable “_speed” gives in Editor access to customize the speed during testing, while keeping the code hidden to other objects. This can help in keeping movement effects solely to this C# code.

The player is called to the origin on Awake() to have the player ready even if the object is disabled. This is useful to add a quick intro and a “start game” button, having the player ready before displaying it on screen.

Calling the CalculateMovement() function in the Update() function will constantly check for player input inside the movement function.

After Update(), let’s write the actual movement function, open a new void and explore each component.

Two float variables to reference the input from the default Horizontal and Vertical Axes that Unity provides with the Input System; in a keyboard, “ws” represent the up and down arrow keys, the vertical axis, while “ad” are horizontal.

A Vector3 called “direction” that is influenced through the input system on the x and y axes, keeping z on 0.

Now that there is a direction, let’s add a force called “_speed”.

This will translate the player by multiplying the Input direction by the speed by time. At this point, movement is implemented.

To add boundaries and avoid camera movement, let’s clamp the higher and lower position:

Mathf.Clamp(transform.position.y, -4f, 1f)

By using the Mathf.Clamp(axis-y, upper boundary , lower boundary) function, the player won’t move higher than 1 or lower than -4 on the y-axis.

Finally, a teleportation effect on the left and right boundaries will keep the player moving in a more intuitive way for a 2D Space Shooter. This code will teleport the player from 11 units on the X-axis to -11, while respecting the input given on the vertical axis on that frame.

And now the space ship moves within these boundaries.

If the input is not causing any movement, make sure the Input System is installed on the Package Manager window.

--

--

Alberto Garcia
Alberto Garcia

No responses yet