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
EasyLet the player steer the cube with the arrow keys.
- In
Update(), whileInput.GetKey(KeyCode.RightArrow)is true, addnew Vector3(speed * Time.deltaTime, 0, 0)totransform.position. - While
KeyCode.LeftArrowis held, take the sameVector3away 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground