In this lesson, you’ll learn how to unify multiple individual key presses into a single directional vector using Input Action Asset composites, simplifying your movement logic.
Why Use Vector Composites?
When handling movement, you traditionally have to check four separate keys (W, A, S, D) and manually calculate the direction. This leads to messy, repetitive code. Unity’s Input System solves this by providing 2D Vector Composites. Instead of checking "is W pressed?" and "is S pressed?" to determine vertical velocity, the system collapses these inputs into a single Vector2 automatically.
Configuring the Composite
Inside your Input Action Asset, you can add a new Action (e.g., "Move") and set its Action Type to Value and its Control Type to Vector 2.
- Right-click your "Move" action and select Add Composite.
- Choose 2D Vector.
- This creates a "Vector2" entry with four slots: Up, Down, Left, and Right.
- Assign your WASD keys to these slots.
By choosing Digital Normalized in the composite settings, Unity ensures that if a player holds both 'Up' and 'Right' simultaneously, the resulting vector remains a magnitude of 1, preventing "diagonal speed-boosting" where the player moves faster than they should.
Accessing the Vector in Script
Once configured, your C# script becomes much cleaner. Because the Input System handles the math, you simply read the Vector2 value directly from the callback context:
private Vector2 moveInput;
public void OnMove(InputAction.CallbackContext context)
{
// The composite already combined the keys into one vector
moveInput = context.ReadValue<Vector2>();
}
void FixedUpdate()
{
// Apply the composite vector to your Rigidbody2D
rb.velocity = moveInput * speed;
}
By using composites, you treat movement as a directional heading rather than a series of individual button states. This makes your code more readable, modular, and easier to expand for gamepads, where the joystick naturally provides a composite vector without any extra work.
Key Takeaway: Using 2D Vector Composites inside the Input Action Asset allows you to map multiple inputs into a single Vector2, eliminating manual calculation and ensuring consistent diagonal movement speeds.