Steer with the Keys
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 5 of 67.
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
EasyLet the player steer the cube: while the right arrow is held, it moves right (along +x) at speed units per second, and while the left arrow is held, it moves left at the same speed. With no key held it stays put.
Press Play, click the game and try the arrows, 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.
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon