Quick, Easy Movements in Unity
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”
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:
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");
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);
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:
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:
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!