Axes
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 13 of 67.
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
EasyThe rover should handle crisply, with no easing: the arrows (or WASD) drive it at speed units per second, left and right along x, up and down along z. It moves at full speed from the moment a key is pressed and stops the moment the key is released.
Press Play, click the game and drive, then press 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.
}
}
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