Quick, Easy Movements in Unity

Mike Brisson
3 min readMar 25, 2021

--

One of the best moments when starting a new game or project is when you are actually able to control your player from your own keyboard. As luck would have it, it is fairly simple to accomplish in Unity.

The first step is finding something to move. You can import an object like an fbx file or simply create one from the Unity menu:

or you can right click on the Hierarchy tab:

Now that you have your Player Object, it’s time for the not-so secret sauce. Right click in the Project window and select Create>C# Script and name it “Movement”

You can name the script anything but be sure to Capitalize the first letter and DON’T use spaces in the naming

Now double click on the script you just created which should automatically load your default script editor.

You should be welcomed with a file similar to below:

Colors/Fonts may vary

What you are looking at is what Unity adds by default to any new script. This may seem overwhelming but we are only going to focus on one small section…the “void Update()” section:

In between the curly braces, we are going to type 2 lines of text:

 
var left = Input.GetAxis("Horizontal");
var up = Input.GetAxis("Vertical");
Be mindful of the case sensitive text along with quotations and semi-colons

At this point, we have essentially told Unity to access the input from the WASD keys (Horizontal and Vertical Axis) every frame (Update). So far we have stored the values in 2 variables (left, up) but we haven’t told Unity to do anything with them yet.

We do that with 1 magic line:

transform.Translate(new Vector2(left, up) * Time.deltaTime);
Time.deltaTime makes the movement frame rate independent, regardless of the CPU speed

Save the file and return to the Unity editor. From here we are going to drag the Movement script onto our player object in the hierarchy:

Forgetting to drag this is onto your object is a common mistake

All that is left to do is to click on the play at the top of the editor and click on the WASD keys to watch your object move:

You may have to click on the Game window for Unity to read your inputs

SUCCESS…you have created your first player movement script and now you are a virtual puppet master! One last thing we can do to speed up our movement is to add a speed variable.

The best practice for this is to add one that can be accessed while playing. At the top of the file, under the first curly brace, type:

public float speed = 5f;

Now that we have introduced the variable, we need to add it to our last line and your text should look like this:

Not only have we increased the speed, but we now have access to change the speed at runtime:

You now have control over speed and movement of your player!

--

--

No responses yet