Unity: Basic Movement

  • Requirement: Unity
  • Language: C#
  • Difficulty: Easy
  • Written by: Lee Zhi Eng
  • Last update: 29 Aug 2019

Introduction

In this tutorial, we will learn how to move a game object/character using the easiest method provided by Unity and get you started in creating your first game.

Direct Object Movement

The easiest way to move a game object is to alter its position data directly every frame. This method is widely used in simpler games but may not be suitable for more complex ones. We will talk more about this later in this chapter. Before that, let’s write our first line of code!

Create a C# script by going to Assets 🡒 Create 🡒 C# Script and name your file movement.cs. By default, your script looks exactly like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
    }
}

The 3 lines at the top indicates the inclusion of basic classes required for your script to work in Unity.

The code below it declares the movement class which carries the same name as the script. Within the class are two built-in functions already declared for you, which is the Start and Update functions.

  • Start – The Start function only run once when the game starts. You may instantiate game objects or initialize variables here.
  • Update – This function runs every tick/frame (if your game runs at 60fps, this function will be called 60 times per second), please be extremely careful when adding code to this function.

Let’s start writing some code, shall we? Let’s add the following lines to the Update function:

void Update()
{
    Vector3 pos = transform.position;
    pos.x += 2;
    transform.position = pos;
}

The code above saves the current position data of the game object into a Vector3 variable called pos. Then, we add 2 units to its x-axis and set the pos variable as the new position data. After that, create a cube and place it into your scene. Then, drag and drop the script from the asset panel onto the cube.

Drag-and-drop is all you need

Once you see the movement script is now a component on the cube, let’s click on the ► Play button to see what happen. Since the code gets called every tick/frame, the cube will keep on moving 2 units along the x-axis every frame until you stop the game.

If you can’t see anything, make sure to position your camera so that the cube is within the field of view.

Delta Timing

Since the Update function is called every tick/frame, it is very inconsistent and unpredictable. The frame rate may be very different on every device depending on its hardware spec. A high spec device may get very high frame rate (if you don’t cap the frame rate) and a low spec device may get a very low frame rate; this will lead to different player having different movement speed in your game.

To solve this problem, we need to get the delta timing of each frame and multiply it with the movement speed to offset the differences. Delta timing is the time (in milliseconds) passed between the current frame and the previous frame. Fortunately, Unity provides us with this information by default. So all we have to do is to get it from the Time class and multiply it to our movement speed, like so:

void Update()
{
    Vector3 pos = transform.position;
    pos.x += 2 * Time.deltaTime;
    transform.position = pos;
}

Woala! Your movement speed is now consistent across different devices!

Keyboard Input

The most fascinating thing about games is that you as a player is able to control the in-game character and move it around as if you’re the character itself. Therefore, player input is a very important aspect that you need to master as a game programmer.

There are many different ways we can control in-game character – keyboard, mouse, joystick, gamepad, touch screen, etc. Let’s get started with keyboard input as we can test it easily in Unity. To detect if a keyboard button has been pressed, we can use the getKey function from the Input class:

void Update()
{
    Vector3 pos = transform.position;
    if (Input.GetKey(KeyCode.W))
    {
        pos.x += 2 * Time.deltaTime;
    }
    if (Input.GetKey(KeyCode.S))
    {
        pos.x -= 2 * Time.deltaTime;
    }
    transform.position = pos;
}

Since our game character may not face the same direction all the time, we shouldn’t fixed it to the x-axis only. Instead, we can use the forward property from its Transform component to obtain the forward direction (or backward direction if you multiply it with negative value). We also store the speed value into a float variable called speed:

void Update()
{
    Vector3 pos = transform.position;
    float speed = 2;
    if (Input.GetKey(KeyCode.W))
    {
        pos += transform.forward * speed * Time.deltaTime;
    }
    if (Input.GetKey(KeyCode.S))
    {
        pos -= transform.forward * speed * Time.deltaTime;
    }
    transform.position = pos;
}

This way, the game object will always move toward its forward direction whenever the W button is pressed, or move backward if the S button is pressed. Let’s push it further by adding the A button and D button as well.

Since we want to move it to the side this time, we can no longer use the forward property. Instead, we can use the right property to obtain its right direction. We can also get its left direction by simply multiplying the right direction with a negative value. We can also adjust the speed value to alter the movement speed:

void Update()
{
    float speed = 10;
    Vector3 pos = transform.position;
    if (Input.GetKey(KeyCode.W))
    {
        pos += transform.forward * speed * Time.deltaTime;
    }
    if (Input.GetKey(KeyCode.S))
    {
        pos -= transform.forward * speed * Time.deltaTime;
    }
    if (Input.GetKey(KeyCode.A))
    {
        pos -= transform.right * speed * Time.deltaTime;
    }
    if (Input.GetKey(KeyCode.D))
    {
        pos += transform.right * speed * Time.deltaTime;
    }
    transform.position = pos;
}

There you have it. The result looks something like this:

As you can see, the movement is very simple. It moves at a constant speed and doesn’t involve physics (gravity, collision detection, etc.), which works well for simple games but not the more complex ones, such as RPG, RTS, racing games and so on.

Source Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        float speed = 10;
        Vector3 pos = transform.position;
        if (Input.GetKey(KeyCode.W))
        {
            pos += transform.forward * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.S))
        {
            pos -= transform.forward * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.A))
        {
            pos -= transform.right * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.D))
        {
            pos += transform.right * speed * Time.deltaTime;
        }
        transform.position = pos;
    }
}

Leave a Reply