2D Game Development: Player Movement

This article discusses basic 2D movement in Unity.

Basic movement using translation.

Movement is a required action in many games across multiple genres, from shoot ‘em ups to mystery. While movement can be handled in a multitude of ways, in Unity it is handled through translation.

Translation is handled by Vector3 (or a 3x1 matrix, for those versed in math). In Unity, there are six preset Vector3 dedicated towards movement: Up, down, left, right, forward, and back. For our purposes, we need only to concern ourselves with the first four. To move in a straight line without player input is relatively simple, requiring one line of code in the Update method:

Causes a gameobject to move (1,0,0)/second (Note: without the multiplication to Time.deltaTime the gameobject would move (60,0,0)/second)

While effective for projectiles or basic enemy movement, this does not allow for user input nor different directions. To do this, we must utilize the Input class. For player movement along the X axis, the horizontal axis must be grabbed and stored in a variable. Once stored, the variable must be multiplied with the vector.

Allows for the player to move an object left and right through the left/right arrow keys. To change controls, go to Edit>Project Settings and then select “Input Manager.”

The same applies to the moving up and down, just add an additional variable for the vertical axis and an additional translation to boot. The end product should look something like this:

Finished product allowing for movement in all four directions.

This can also be cut down into one line (excluding the variables) by replacing the initial Vector3 with a new Vector 3 composing of the horizontal and vertical inputs ((hInput, vInput, 0)). While this works as a basic way to control an object, this is unable to change speed. To do this, a new variable must be implemented, which is discussed here.



Aspiring to be aUnity game developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store