Skip to main content

How to: Arrow Key movement

This page lists 3 ways to respond to arrow key presses in your game. You can mix and match these approaches as you see fit. The first approach (via the joystick) is the simplest way and so you should start with that, and only go to the other approaches if you need more control or customizability.

Via Joystick

The simplest way to respond to all four arrow key directions is to use Joystick as your input method. Easel automatically maps arrow keys to the joystick if no other code in your codebase refers to the arrow keys.

pub game fn World.Main() {
SpawnEachPlayer owner {
Subspawn unit {
Hero
}
}
}

pub fn unit.Hero([owner]) {
use body=unit

Body(pos=@(0,0))
PolygonSprite(shape=Equilateral(radius=1, numPoints=3), color=#00ff00)

on BeforePhysics {
if Joystick == @(0, 0) { continue }
Heading = Angle(Joystick)
Move(0.25 * Joystick)
}
}

WASD keys will also automatically be mapped to the joystick as well if they are not used either. See Input Unification for more details on how this works.

Using IsButtonDown

Alternatively, you can check if a particular button is pressed using IsButtonDown. This gives you greater control and customizability,

pub game fn World.Main() {
SpawnEachPlayer owner {
Subspawn unit {
Hero
}
}
}

pub fn unit.Hero([owner]) {
use body=unit

Body(pos=@(0,0))
PolygonSprite(shape=Equilateral(radius=1, numPoints=3), color=#00ff00)

on BeforePhysics {
let step = @(0, 0)
if IsButtonDown(ArrowUp) { step -= @(0, 1) }
if IsButtonDown(ArrowDown) { step += @(0, 1) }
if IsButtonDown(ArrowLeft) { step -= @(1, 0) }
if IsButtonDown(ArrowRight) { step += @(1, 0) }

if step == @(0, 0) { continue }
Heading = Angle(step)
Move(0.25 * step)
}
}

Using ButtonDown and ButtonUp

Another approach is to button presses using ButtonDown and ButtonUp events.

pub game fn World.Main() {
SpawnEachPlayer owner {
Subspawn unit {
Hero
}
}
}

pub fn unit.Hero([owner]) {
use body=unit
let speed = 10

Body(pos=@(0,0))
PolygonSprite(shape=Circle(radius=1), color=#00ff00)

on ButtonDown(ArrowUp) { Velocity -= @(0, speed) }
on ButtonUp(ArrowUp) { Velocity += @(0, speed) }
on ButtonDown(ArrowDown) { Velocity += @(0, speed) }
on ButtonUp(ArrowDown) { Velocity -= @(0, speed) }
on ButtonDown(ArrowLeft) { Velocity -= @(speed, 0) }
on ButtonUp(ArrowLeft) { Velocity += @(speed, 0) }
on ButtonDown(ArrowRight) { Velocity += @(speed, 0) }
on ButtonUp(ArrowRight) { Velocity -= @(speed, 0) }
}