Another common trigger is the one where an action from the player is required. For example, you can use it to open a door, or access an in-game store system or dialog.
InteractionTrigger
, which extends Trigger
and also implements ActionListener
.InteractionTrigger
class needs a Vector3f
field called position, a BoundingVolume
field called volume
, a Spatial
field called player
, and a boolean
field called inside
.InteractionTrigger
class needs access to the application's guiNode
, which we store in a Node
field with the same name and a BitmapText
field called interactionPrompt
. The text will be displayed when interaction is possible.INTERACTION_KEY = "Interact"
either in this class or the input manager
classupdate
method will check whether the player is inside BoundingVolume
. If it is and inside
is false
, it will show interactionPrompt
. On the other hand, if inside
is true
and the player is not inside BoundingVolume
, it will remove it, as shown in the following code:Boolean contains = volume.contains(player.getWorldTranslation()); if(!inside && contains){ guiNode.attachChild(interactionPrompt); } else if (inside && !contains){guiNode.detachChild(interactionPrompt); } inside = contains;
onAction
method, we check for when the key corresponding to INTERACTION_KEY
is released. Then, we see whether the trigger is enabled and whether inside
is true
or not. If both are true
, we call trigger()
.guiNode
and BitmapText
to the trigger, the INTERACTION_KEY
needs to be bound to inputManager
. This can be done with the following line:inputManager.addMapping(INTERACTION_KEY, new KeyTrigger(KeyInput.KEY_SPACE));
InteractionTrigger
instance also needs to be added as a listener to inputManager
:inputManager.addListener(interactionTrigger, mappingNames);
The InteractionTrigger
instance has several things in common with EnterableTrigger
, which we created in the Creating a trigger system recipe, and it also has a new functionality. Rather than firing the trigger as soon as the player enters it, it sets the inside
flag, which defines whether it's possible to interact with it or not. It also displays a text on the GUI for the player.
Once the InteractionTrigger
receives a call to its onAction
method from InputManager
, it checks whether inside
is true
and calls trigger
. To brush up your knowledge on how input is handled, check out Chapter 2, Cameras and Game Control.
18.225.57.164