Simple Player Movement in Unity

Manuel Cabacungan
4 min readAug 13, 2021

--

Objective: Start by making the player game object move automatically at the beginning of the game.

In Unity, every object in the Scene and Hierarchy panes is a game object which has properties for position, rotation and scale that can be seen in the Inspector pane.

In the example above, I already made a cube game object and renamed it “Player”. Let’s make a new C# script in the “Scripts” folder and call it “Player” as well. Be sure to rename it just after you create the C# file because the class will be given the name of the file name. Next, double click the Player C# script and it will open in Visual Studio.

Every C# script is given a default C# template that start with declarations for name spaces that start with “using” for standard Unity C# libraries, a class with the file name used as the class name, and nested inside the class are two procedures: Start() and Update(). Start() executes at the beginning of the game. Update() executes once per frame update.

Default Unity C# Template

The initial starting point of the object can be set in the Start() procedure by directly referencing the object’s position properties with:

transform.position

You can change the position by assigning new x,y and z values using a Vector3 () variable to hold the new position value.

transform.position = new Vector3(0, 0, 0);

In this case, we want to just snap the player to the origin position (0, 0, 0)

When we test this out, the player cube snaps to the origin.

For continuous movement of a Unity game object, we will add code inside the Update() procedure. The Translate() method allows us to continuously move the player game object.

transform.Translate()

When a game object in the Heirarchy panel is selected, its properties are displayed in the Inspector panel in which the Transform panel has an icon (?) for the Unity manual documentation for this Transform panel.

The Unity manual documentation has a link for the scripting reference where we can find the Translate method and the proper syntax for using it.

As an example, if we want the player object to move to the left, we can follow the code example in the documentation but just use the shortcut “left” instead of the shortcut “forward” that was in the code example.

transform.Translate(Vector3.left * Time.deltaTime);

“Time.deltatime” forces the movement to happen at a consistent rate regardless of the speed of the processor running this.

If we test that, the player object moves very slowly at approximately 1 meter per second.

To speed it up, we can just multiply it by 5:

transform.Translate(Vector3.left * 5 * Time.deltaTime);

Now when we test this, the player cube moves faster.

In the next article, we will discuss using variables so that the speed will not be hard-coded into the movement line of code.

--

--