2D Game Development: Player Movement
This article discusses basic 2D movement in Unity.
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:
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.
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:
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.