JME 3 Tutorial (5) - Hello Input System

Previous: Hello Update Loop, Next: Hello Material

By default, SimpleApplication sets up an input system that allows you to steer the camera with the WASD keys, the arrow keys, and the mouse. You can use it as a flying first-person camera right away. But what if you need a third-person camera, or you want keys to trigger special game actions?

Every game has its custom keybindings, and this tutorial explains how you define them. We first define the key presses and mouse events, and then we define the actions they should trigger.

Sample Code

package jme3test.helloworld;
 
import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
import com.jme3.math.ColorRGBA;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.AnalogListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.input.controls.MouseButtonTrigger;
 
/** Sample 5 - how to map keys and mousebuttons to actions */
public class HelloInput extends SimpleApplication {
 
  public static void main(String[] args) {
    HelloInput app = new HelloInput();
    app.start();
  }
  protected Geometry player;
  Boolean isRunning=true;
 
  @Override
  public void simpleInitApp() {
    Box(Vector3f.ZERO, 1, 1, 1);
    player = new Geometry("Player", b);
    Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    mat.setColor("Color", ColorRGBA.Blue);
    player.setMaterial(mat);
    rootNode.attachChild(player);
    initKeys(); // load my custom keybinding
  }
 
  /** Custom Keybinding: Map named actions to inputs. */
  private void initKeys() {
    // You can map one or several inputs to one named action
    inputManager.addMapping("Pause",  new KeyTrigger(KeyInput.KEY_P));
    inputManager.addMapping("Left",   new KeyTrigger(KeyInput.KEY_J));
    inputManager.addMapping("Right",  new KeyTrigger(KeyInput.KEY_K));
    inputManager.addMapping("Rotate", new KeyTrigger(KeyInput.KEY_SPACE),
                                      new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
    // Add the names to the action listener.
    inputManager.addListener(actionListener, new String[]{"Pause"});
    inputManager.addListener(analogListener, new String[]{"Left", "Right", "Rotate"});
 
  }
 
  private ActionListener() {
    public void onAction(String name, boolean keyPressed, float tpf) {
      if (name.equals("Pause") && !keyPressed) {
        isRunning = !isRunning;
      }
    }
  };
 
  private AnalogListener analogListener = new AnalogListener() {
    public void onAnalog(String name, float value, float tpf) {
      if (isRunning) {
        if (name.equals("Rotate")) {
          player.rotate(0, value*speed, 0);
        }
        if (name.equals("Right")) {
          Vector3f v = player.getLocalTranslation();
          player.setLocalTranslation(v.x + value*speed, v.y, v.z);
        }
        if (name.equals("Left")) {
          Vector3f v = player.getLocalTranslation();
          player.setLocalTranslation(v.x - value*speed, v.y, v.z);
        }
      } else {
        System.out.println("Press P to unpause.");
      }
    }
  };
}

Build and run the example.

Defining Mappings and Triggers

First you register each mapping name with its trigger(s). Remember the following:

Have a look at the code:

  1. You register the mapping named "Rotate" to the Spacebar trigger
    new KeyTrigger(KeyInput.KEY_SPACE)).
  2. In the same line, you also register "Rotate" to the mouse button trigger
    new MouseButtonTrigger(MouseInput.BUTTON_LEFT)
  3. You map the Pause, Left, Right mappings to the P, J, K keys, respectively.
  4. You register the (on/off) pause action to the ActionListener
  5. You register the (gradual) movement actions to the AnalogListener
    // You can map one or several inputs to one named action
    inputManager.addMapping("Pause",  new KeyTrigger(KeyInput.KEY_P));
    inputManager.addMapping("Left",   new KeyTrigger(KeyInput.KEY_J));
    inputManager.addMapping("Right",  new KeyTrigger(KeyInput.KEY_K));
    inputManager.addMapping("Rotate", new KeyTrigger(KeyInput.KEY_SPACE),
                                      new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
    // Add the names to the action listener.
    inputManager.addListener(actionListener, new String[]{"Pause"});
    inputManager.addListener(analogListener, new String[]{"Left", "Right", "Rotate"});

This code usually goes into the simpleInitApp() method. But since we will likely add many keybindings, we extract these lines and wrap them in an auxiliary method, initKeys(). The initKeys() method is not part of the Input Controls interface – so you can name it whatever you like. Just don't forget to call your method from the initSimpleApp() method.

Implementing the Actions

Now you have mapped action names to input triggers. Now you specify the actions themselves.

The two important methods here are the ActionListener with its onAction() method, and the AnalogListener with its onAnalog() method. In these two methods, you test for each named mapping, and call the game action you want to trigger.

In this example, we set the following mappings:

  1. The Rotate mapping triggers the action player.rotate(0, value, 0).
  2. The Left and Right mappings increase and decrease the player's x coordinate.
  3. The Pause mapping flips a boolean isRunning.
  4. We also want to check the boolean isRunning before any action (other than unpausing) is executed.
  private ActionListener() {
    public void onAction(String name, boolean keyPressed, float tpf) {
      if (name.equals("Pause") && !keyPressed) {
        isRunning = !isRunning;
      }
    }
  };
 
  private AnalogListener analogListener = new AnalogListener() {
    public void onAnalog(String name, float value, float tpf) {
      if (isRunning) {
        if (name.equals("Rotate")) {
          player.rotate(0, value*speed, 0);
        }
        if (name.equals("Right")) {
          Vector3f v = player.getLocalTranslation();
          player.setLocalTranslation(v.x + value*speed, v.y, v.z);
        }
        if (name.equals("Left")) {
          Vector3f v = player.getLocalTranslation();
          player.setLocalTranslation(v.x - value*speed, v.y, v.z);
        }
      } else {
        System.out.println("Press P to unpause.");
      }
    }
  };

It's okay to use only one of the two Listeners, and not implement the other one, if you are not using this type of interaction. In the following, we have a closer look how to decide which of the two listeners is best suited for which situation.

Analog, Pressed, or Released?

Technically, every input can be an "Analog" or a "on-off Action". Here is how you find out which listener is the right one for which type of input.

Mappings registered to the AnalogListener are triggered repeatedly and gradually.

Mappings registered to the ActionListener are treated in an absolute way – "Pressed or released? On or off?"

Tip: It's very common that you want an action to be only triggered once, in the moment when the key is released. For instance when opening a door, flipping a boolean state, or picking up an item. To achieve that, you use an ActionListener and test for … && !keyPressed. For an example, look at the Pause button code.

      if (name.equals("Pause") && !keyPressed) {
        isRunning = !isRunning;
      }

Table of Triggers

You can find the list of input constants in the files src/core/com/jme3/input/KeyInput.java, JoyInput.java, and MouseInput.java. Here is an overview of the most common triggers constants:

Trigger Code
Mouse button: Left Click MouseButtonTrigger(MouseInput.BUTTON_LEFT)
Mouse button: Right Click MouseButtonTrigger(MouseInput.BUTTON_RIGHT)
Keyboard: Characters and Numbers KeyTrigger(KeyInput.KEY_X)
Keyboard: Spacebar KeyTrigger(KeyInput.KEY_SPACE)
Keyboard: Return, Enter KeyTrigger(KeyInput.KEY_RETURN), KeyTrigger(KeyInput.KEY_NUMPADENTER)
Keyboard: Escape KeyTrigger(KeyInput.KEY_ESCAPE)
Keyboard: Arrows KeyTrigger(KeyInput.KEY_UP), KeyTrigger(KeyInput.KEY_DOWN)
KeyTrigger(KeyInput.KEY_LEFT), KeyTrigger(KeyInput.KEY_RIGHT)

Tip: If you don't recall an input constant during development, you benefit from an IDE's code completion functionality: Place the caret after e.g. KeyInput.| and trigger code completion to select possible input identifiers.

Exercises

  1. Add mappings for moving the player (box) up and down with the H and L keys.
  2. Modify the mappings so that you can also trigger the up an down motion with the mouse scroll wheel.
    • Tip: Use new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true)
  3. In which situation would it be better to use variables for the MouseInput/KeyInput definitions?
    int usersPauseKey = KeyInput.KEY_P;
    ...
    inputManager.addMapping("Pause",  new KeyTrigger(usersPauseKey));

Conclusion

You now how to add custom interactions to your game: You know now that you first have to define the key mappings, and then the actions for each mapping. You have learned to respond to mouse events and to the keyboard. You understand the difference between "analog" (gradually repeated) and "digital" (on/off) inputs.

Now you can already write a little interactive game! But wouldn't it be cooler if these old boxes were a bit more fancy? Let's continue with learning about materials.

input, intro, beginner, beginner,, documentation, keyinput, click

view online version