Let’s Get Moving — Movement in Unity
In this example, I will be creating a 2D top down shooter style game akin to Galaga or Space Invaders.
The first step will be giving the player control of their character. During this time, I will be using placeholder geometric shapes. The player will consist of a cube for now.
In a new Unity Project, I created a Cube object and a new C# script.
I rename the Cube to Player, and the C# Script to PlayerController.
Attach the script by dragging it from the Project window onto the Player (Cube) in the Hierarchy Window.
Now Open up the C# script by double clicking it, and we can get started on the logic.
First off, I create a float variable to hold my intended player’s speed. I name it _speed.
Next, I want the player to always start the game at 0,0,0 coordinates. In Void Start (which is called on the first frame of the game), I add the following:
Next, I create a new Void called Movement. I do this to keep my code compartmentalized and easier to edit for myself or for any contributors also working in the code.
Inside of Movement, I create two local float variables. These variables only apply to the logic inside of the Movement Void.
This code utilizes Unity’s built in understanding of “Horizontal” and “Vertical”. This will allow us to move using the arrow keys as well as WASD.
Finally, I add the logic for translating (which is just the technical term for moving) for each of the two axis’.
I multiply the movement by the axis I want to move on, the speed variable I set (I set mine to 5), and finally time.deltatime to keep the speed time locked and appropriate for use.
Now in Void Update, I add my Movement function like so:
Void Update runs every frame. This means that every frame, my movement code will be called, allowing for easy and intuitive movement for the player.
And that’s it! Movement on a 2D plane could not be simpler when using Unity!