Buttons API
The Buttons API (a.k.a Input bindings) allows you to use the same event for mouse, keyboard, and gamepad.
You can set generic names like jump
and bind it to the keys, gamepad/mouse buttons
you want.
Creating input bindings
You have to define the initial input bindings in the KAPLAYOpt.buttons
option in kaplay()
, passing
a ButtonsDef
object:
kaplay({
buttons: {
jump: {
keyboard: ["space", "up"], // You can bind various buttons...
gamepad: "south", // ...Or just one
},
},
});
Listening to input bindings
After setting your input bindings, you can use the different input handlers to listen to the buttons:
There’s a list with all handlers, with its boolean versions:
Boolean | Handler |
---|---|
isButtonPressed() | onButtonPress() |
isButtonDown() | onButtonDown() |
isButtonReleased() | onButtonRelease() |
Getting and setting buttons
Maybe you want dynamically change the bindings in your game. Depending for example of a configuration or a level.
You can use the getButton(btn)
and setButton(btn)
to get and set
input bindings, it perfoms a shallow merge, so the devices you don’t change:
stays the same.
// Get jump binding for keyboard
getButton("jump").keyboard;
// Set new binding for jump with keyboard, keeping gamepad
setButton("jump", {
keyboard: ["w"],
});
Trigger buttons virtually
Sometimes there’s a need to trigger a button virtually, for example when you want to simulate a button press in mobile or in a cutscene.
You can use pressButton(btn)
and releaseButton(btn)
to trigger the button:
pressButton("jump"); // triggers onButtonPress and starts onButtonDown
releaseButton("jump"); // triggers onButtonRelease and stops onButtonDown