Handling Analog Controller Input Values
In this lesson, you will learn how to capture continuous, multi-directional joystick data to translate controller movement into smooth character navigation.
When you move an analog stick on a gamepad, the controller doesn't just send a simple "on" or "off" signal like a keyboard button. Instead, it sends a continuous range of values representing both the magnitude (how far the stick is pushed) and the direction (the angle). In the new Input System, this data is delivered as a Vector2.
Processing Vector2 Data
The x component of the Vector2 represents the horizontal movement (left and right), while the y component represents vertical movement (up and down). Because these values range from -1 to 1, they are perfect for controlling velocity.
To process this, you subscribe to an InputAction using the performed callback. Whenever the joystick moves, the system passes a CallbackContext object containing the current Vector2 state.
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private Vector2 moveInput;
// This method is triggered by your "Move" action
public void OnMove(InputAction.CallbackContext context)
{
// Read the continuous Vector2 value from the stick
moveInput = context.ReadValue<Vector2>();
}
void Update()
{
// Apply the input to movement (using your Transform knowledge)
transform.position += new Vector3(moveInput.x, 0, moveInput.y) * Time.deltaTime;
}
}
Why This Matters
By using the Vector2 directly, you allow your character to move at different speeds. If a player pushes the stick only halfway, the Vector2 will report values like (0.5, 0.5) instead of (1, 1), resulting in a gentle walk rather than a full-speed run.
Because we are storing this value in a class-level variable (moveInput), the Update method can access the "current" state of the controller every single frame. This decouples the input detection (the callback) from the movement logic (the Update loop), ensuring your character feels responsive and fluid regardless of how the analog stick is manipulated.
Key Takeaway: Analog inputs provide a continuous Vector2 that allows for nuanced, variable-speed movement by mapping stick displacement directly to your object's translation.