Menu
CoddyTech

Steer with the Keys

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 12 of 85.

Input.GetKey(KeyCode.Space) is true on every frame while Space is held down and false otherwise. Ask it in Update() and move only when it says yes, and the player steers the object.

This crate rises at lift units per second while Space is held. Time.deltaTime keeps the speed per second, as in the last lesson:

public float lift = 2f;

void Update()
{
    if (Input.GetKey(KeyCode.Space))
    {
        transform.position += new Vector3(0, lift * Time.deltaTime, 0);
    }
}

Every key has a KeyCode: KeyCode.UpArrow, KeyCode.W, KeyCode.Return and so on. Click the game view first so the keys reach it. A note for Unity 6: new projects use the new Input System, and Input.GetKey throws an error there until Active Input Handling (Project Settings, Player) is set to Both.

challenge icon

Challenge

Easy

Let the player steer the cube with the arrow keys.

  1. In Update(), while Input.GetKey(KeyCode.RightArrow) is true, add new Vector3(speed * Time.deltaTime, 0, 0) to transform.position.
  2. While KeyCode.LeftArrow is held, take the same Vector3 away with -=.

Press Play, click the game and hold the arrows: the cube slides right and left. Then Check.

Try it yourself

using UnityEngine;

public class Steering : MonoBehaviour
{
    public float speed = 4f;

    void Update()
    {
        // Right arrow: move right. Left arrow: move left.
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground