Let’s Get Moving — Movement in Unity

Jack Leavey
3 min readMay 17, 2022

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.

The Player

In a new Unity Project, I created a Cube object and a new C# script.

Creating a new cube from the Hierarchy.
Creating 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.

A new script should look like this.

First off, I create a float variable to hold my intended player’s speed. I name it _speed.

Remember to set your applicable variables for any programming.

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:

This tells my player gameobject to be at 0,0,0 when the game starts, regardless of where they actually were.

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!

--

--

Jack Leavey

I am a software engineer with years of experience branching into game development, specifically in Unity. Follow along for guides on creating game mechanics!