Adding an interaction trigger

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.

How to do it...

  1. We begin by creating a new class called InteractionTrigger, which extends Trigger and also implements ActionListener.
  2. The InteractionTrigger class needs a Vector3f field called position, a BoundingVolume field called volume, a Spatial field called player, and a boolean field called inside.
  3. Furthermore, the 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.
  4. We also have to define a static string called INTERACTION_KEY = "Interact" either in this class or the input manager class
  5. The update 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;
  6. In the implemented 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().
  7. Some logic outside the class is required to get the trigger to work. Apart from supplying 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));
  8. The InteractionTrigger instance also needs to be added as a listener to inputManager:
    inputManager.addListener(interactionTrigger, mappingNames);

How it works...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.57.164