Axes
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 20 of 85.
Input.GetAxis("Horizontal") turns the left and right arrows (and A and D) into one number from -1 to 1: -1 for left, 1 for right, 0 for neither. Input.GetAxis("Vertical") does the same for the down and up arrows (S and W). One call replaces two ifs, and a gamepad stick drives the same axes with no extra code.
The number does not jump. With Unity's default settings it moves toward its target at 3 per second, so it takes a third of a second to reach 1 after a press and another third to fall back to 0 after the release. That easing makes this hovercraft speed up gently and drift to a stop:
public float speed = 5f;
void Update()
{
float h = Input.GetAxis("Horizontal");
transform.position += new Vector3(h * speed * Time.deltaTime, 0, 0);
}Input.GetAxisRaw("Horizontal") skips the easing: it is exactly -1, 0 or 1 on every frame, so movement starts and stops at once. Use GetAxis for things that should feel heavy and GetAxisRaw for crisp controls. With both arrows held, either one gives 0, because the two directions cancel out. (In a Unity 6 project, the Active Input Handling setting from Steer with the Keys applies to axes too.)
Challenge
EasyMake the rover drive crisply, with no easing.
- In
Update(), readfloat h = Input.GetAxisRaw("Horizontal");andfloat v = Input.GetAxisRaw("Vertical");. - Add
new Vector3(h * speed * Time.deltaTime, 0, v * speed * Time.deltaTime)totransform.position.
Press Play, click the game and drive with the arrows or WASD: the rover starts and stops at once. Then Check.
Try it yourself
using UnityEngine;
public class Rover : MonoBehaviour
{
public float speed = 4f;
void Update()
{
// Horizontal drives along x, Vertical along z, with no easing.
}
}
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