How to move an object with the keyboard in Unity

In by John FrenchPublished

To move an object with the keyboard, or with any other input device, simply multiply the direction of movement you want to apply, such as forward, for example, by the Input Axis you want to use to control it.

In Unity, when using the default Input Manager, you’ll find an Input Axis for Horizontal and Vertical movement already set up and mapped to the WASD keys and arrow keys on the keyboard.

Each axis returns a value between -1 and 1, which means that you can use the value that’s returned to create a movement vector.

Like this:

public float speed = 2;

void Update()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(x, 0, z);
    transform.Translate(movement * speed * Time.deltaTime);
}

This allows you to create object-relative movement controls using the keyboard or any other input device.

See also: