-
-
Notifications
You must be signed in to change notification settings - Fork 711
Input
In this tutorial we go through various approaches that allow you to handle user input.
Note: we are only going to cover FXGL input handling. However, if you ever needed for any reason, you can obtain a reference to the underlying JavaFX Scene object: getGameScene().getRoot().getScene() and use JavaFX handling.
Any input (currently keyboard & mouse) is captured by FXGL internally and handled by a UserAction that is specified by the developer. A UserAction has three states:
- BEGIN (1 tick)
- ACTION (1 or more ticks)
- END (1 tick)
Those states correspond to the user pressing, holding and releasing a key or a mouse button. This 3-state system allows us to provide an easy high-level API for handling any type of input. Consider a UserAction for hitting a golf ball:
UserAction hitBall = new UserAction("Hit") {
@Override
protected void onActionBegin() {
// action just started (key has just been pressed), play swinging animation
}
@Override
protected void onAction() {
// action continues (key is held), increase swing power
}
@Override
protected void onActionEnd() {
// action finished (key is released), play hitting animation based on swing power
}
};Now that we have created an action hitBall, we can ask the input service to register it:
@Override
protected void initInput() {
Input input = getInput();
input.addAction(hitBall, KeyCode.F);
}The second parameter to addAction() is the trigger. The trigger can either be a key or a mouse button.
We say that "action" is bound to "trigger", so in this case the hitBall action is bound to the F key.
TODO (addInputBinding)
TODO (isHeld, getMouseXY)
- Actions must have unique and meaningful names.
- One action <-> one trigger policy, i.e. an action is bound to a single trigger and only a single action can be bound to a trigger.