How to: Multiple Input Methods
Let's say you are making a game where you want the player to be able to move with the arrow Keys, WASD, a gamepad and a touchscreen joystick. How can you support all of these at once?
The trick is to nominate one input method as the canonical input method for your game, and then remap all other input methods to that canonical input method. It is simplest to use the Joystick as your canonical input method, and so that is what we will do in this example.
pub game fn World.Main() {
KeyboardVirtualJoystick(up=ArrowUp, left=ArrowLeft, down=ArrowDown, right=ArrowRight)
ButtonRemap(KeyW, ArrowUp)
ButtonRemap(KeyA, ArrowLeft)
ButtonRemap(KeyS, ArrowDown)
ButtonRemap(KeyD, ArrowRight)
SpawnEachPlayer owner {
BottomLeftCommand<joystick>(offset=@(6,6)) {
TouchscreenOnly {
VirtualJoystick(radius=5)
}
}
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) {
await Joystick // let the Hero sleep when there is no input
continue
}
Heading = Angle(Joystick)
Move(0.25 * Joystick)
}
}
- KeyboardVirtualJoystick maps the arrow keys to the Joystick.
- ButtonRemap remaps the WASD keys to the arrow keys, which are already mapped to the Joystick.
- VirtualJoystick displays a virtual joystick on the screen. It is wrapped in a TouchscreenOnly UI element so that it is only displayed to touchscreen users.
tip
Note that, because of automatic input unification, Easel actually automatically maps Arrows keys and WASD to the Joystick. This example explicitly shows how to do it manually, just in case you need to because you want to directly read the arrow keys or WASD for some other purpose in your game.