hello_input_system.adoc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. = jMonkeyEngine 3 Tutorial (5) - Hello Input System
  2. :revnumber: 2.1
  3. :revdate: 2020/07/15
  4. :keywords: input, intro, beginner, documentation, keyinput, click
  5. By default, SimpleApplication sets up a camera control that allows you to steer the camera with the kbd:[W] kbd:[A] kbd:[S] kbd:[D] 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?
  6. 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.
  7. == Sample Code
  8. [source,java]
  9. ----
  10. package jme3test.helloworld;
  11. import com.jme3.app.SimpleApplication;
  12. import com.jme3.material.Material;
  13. import com.jme3.math.Vector3f;
  14. import com.jme3.scene.Geometry;
  15. import com.jme3.scene.shape.Box;
  16. import com.jme3.math.ColorRGBA;
  17. import com.jme3.input.KeyInput;
  18. import com.jme3.input.MouseInput;
  19. import com.jme3.input.controls.ActionListener;
  20. import com.jme3.input.controls.AnalogListener;
  21. import com.jme3.input.controls.KeyTrigger;
  22. import com.jme3.input.controls.MouseButtonTrigger;
  23. /**
  24. * Sample 5 - how to map keys and mousebuttons to actions
  25. */
  26. public class HelloInput extends SimpleApplication {
  27. public static void main(String[] args) {
  28. HelloInput app = new HelloInput();
  29. app.start();
  30. }
  31. protected Geometry player;
  32. private boolean isRunning = true;
  33. @Override
  34. public void simpleInitApp() {
  35. Box b = new Box(1, 1, 1);
  36. player = new Geometry("Player", b);
  37. Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
  38. mat.setColor("Color", ColorRGBA.Blue);
  39. player.setMaterial(mat);
  40. rootNode.attachChild(player);
  41. initKeys(); // load my custom keybinding
  42. }
  43. /**
  44. * Custom Keybinding: Map named actions to inputs.
  45. */
  46. private void initKeys() {
  47. // You can map one or several inputs to one named action
  48. inputManager.addMapping("Pause", new KeyTrigger(KeyInput.KEY_P));
  49. inputManager.addMapping("Left", new KeyTrigger(KeyInput.KEY_J));
  50. inputManager.addMapping("Right", new KeyTrigger(KeyInput.KEY_K));
  51. inputManager.addMapping("Rotate", new KeyTrigger(KeyInput.KEY_SPACE),
  52. new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
  53. // Add the names to the action listener.
  54. inputManager.addListener(actionListener, "Pause");
  55. inputManager.addListener(analogListener, "Left", "Right", "Rotate");
  56. }
  57. private final ActionListener actionListener = new ActionListener() {
  58. @Override
  59. public void onAction(String name, boolean keyPressed, float tpf) {
  60. if (name.equals("Pause") && !keyPressed) {
  61. isRunning = !isRunning;
  62. }
  63. }
  64. };
  65. private final AnalogListener analogListener = new AnalogListener() {
  66. @Override
  67. public void onAnalog(String name, float value, float tpf) {
  68. if (isRunning) {
  69. if (name.equals("Rotate")) {
  70. player.rotate(0, value * speed, 0);
  71. }
  72. if (name.equals("Right")) {
  73. Vector3f v = player.getLocalTranslation();
  74. player.setLocalTranslation(v.x + value * speed, v.y, v.z);
  75. }
  76. if (name.equals("Left")) {
  77. Vector3f v = player.getLocalTranslation();
  78. player.setLocalTranslation(v.x - value * speed, v.y, v.z);
  79. }
  80. } else {
  81. System.out.println("Press P to unpause.");
  82. }
  83. }
  84. };
  85. }
  86. ----
  87. Build and run the example.
  88. * Press the Spacebar or click to rotate the cube.
  89. * Press the kbd:[J] and kbd:[K] keys to move the cube.
  90. * Press kbd:[P] to pause and unpause the game. While paused, the game should not respond to any input, other than kbd:[P].
  91. == Defining Mappings and Triggers
  92. First you register each mapping name with its trigger(s). Remember the following:
  93. * An input trigger can be a key press or mouse action.
  94. ** For example a mouse movement, a mouse click, or pressing the letter kbd:[P] .
  95. * The mapping name is a string that you can choose.
  96. ** The name should describe the action (e.g. "`Rotate`"), and not the trigger. Because the trigger can change.
  97. * One named mapping can have several triggers.
  98. ** For example, the "`Rotate`" action can be triggered by a click and by pressing the spacebar.
  99. Have a look at the code:
  100. . You register the mapping named "`Rotate`" to the Spacebar key trigger. +
  101. `new KeyTrigger(KeyInput.KEY_SPACE)`).
  102. . In the same line, you also register "`Rotate`" to an alternative mouse click trigger. +
  103. `new MouseButtonTrigger(MouseInput.BUTTON_LEFT)`
  104. . You map the `Pause`, `Left`, `Right` mappings to the P, J, K keys, respectively.
  105. +
  106. [source,java]
  107. ----
  108. // You can map one or several inputs to one named action
  109. inputManager.addMapping("Pause", new KeyTrigger(KeyInput.KEY_P));
  110. inputManager.addMapping("Left", new KeyTrigger(KeyInput.KEY_J));
  111. inputManager.addMapping("Right", new KeyTrigger(KeyInput.KEY_K));
  112. inputManager.addMapping("Rotate", new KeyTrigger(KeyInput.KEY_SPACE),
  113. new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
  114. ----
  115. Now you need to register your trigger mappings.
  116. . You register the pause action to the ActionListener, because it is an "`on/off`" action.
  117. . You register the movement actions to the AnalogListener, because they are gradual actions.
  118. +
  119. [source,java]
  120. ----
  121. // Add the names to the action listener.
  122. inputManager.addListener(actionListener,"Pause");
  123. inputManager.addListener(analogListener,"Left", "Right", "Rotate");
  124. ----
  125. This code 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 – you can name it whatever you like. Just don't forget to call your method from the `initSimpleApp()` method.
  126. == Implementing the Actions
  127. You have mapped action names to input triggers. Now you specify the actions themselves.
  128. 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.
  129. In this example, we trigger the following actions:
  130. . The _Rotate_ mapping triggers the action `player.rotate(0, value, 0)`.
  131. . The _Left_ and _Right_ mappings increase and decrease the player's x coordinate.
  132. . The _Pause_ mapping flips a boolean `isRunning`.
  133. . We also want to check the boolean `isRunning` before any action (other than unpausing) is executed.
  134. [source,java]
  135. ----
  136. private final ActionListener actionListener = new ActionListener() {
  137. @Override
  138. public void onAction(String name, boolean keyPressed, float tpf) {
  139. if (name.equals("Pause") && !keyPressed) {
  140. isRunning = !isRunning;
  141. }
  142. }
  143. };
  144. private final AnalogListener analogListener = new AnalogListener() {
  145. @Override
  146. public void onAnalog(String name, float value, float tpf) {
  147. if (isRunning) {
  148. if (name.equals("Rotate")) {
  149. player.rotate(0, value * speed, 0);
  150. }
  151. if (name.equals("Right")) {
  152. Vector3f v = player.getLocalTranslation();
  153. player.setLocalTranslation(v.x + value * speed, v.y, v.z);
  154. }
  155. if (name.equals("Left")) {
  156. Vector3f v = player.getLocalTranslation();
  157. player.setLocalTranslation(v.x - value * speed, v.y, v.z);
  158. }
  159. } else {
  160. System.out.println("Press P to unpause.");
  161. }
  162. }
  163. };
  164. ----
  165. You can also combine both listeners into one, the engine will send the appropriate events to each method (onAction or onAnalog).
  166. For example:
  167. [source,java]
  168. ----
  169. private class MyCombinedListener implements AnalogListener, ActionListener {
  170. @Override
  171. public void onAction(String name, boolean keyPressed, float tpf) {
  172. if (name.equals("Pause") && !keyPressed) {
  173. isRunning = !isRunning;
  174. }
  175. }
  176. @Override
  177. public void onAnalog(String name, float value, float tpf) {
  178. if (isRunning) {
  179. if (name.equals("Rotate")) {
  180. player.rotate(0, value * speed, 0);
  181. }
  182. if (name.equals("Right")) {
  183. Vector3f v = player.getLocalTranslation();
  184. player.setLocalTranslation(v.x + value * speed, v.y, v.z);
  185. }
  186. if (name.equals("Left")) {
  187. Vector3f v = player.getLocalTranslation();
  188. player.setLocalTranslation(v.x - value * speed, v.y, v.z);
  189. }
  190. } else {
  191. System.out.println("Press P to unpause.");
  192. }
  193. }
  194. }
  195. // ...
  196. inputManager.addListener(combinedListener, new String[]{"Pause", "Left", "Right", "Rotate"});
  197. ----
  198. 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.
  199. == Analog, Pressed, or Released?
  200. Technically, every input can be either an "`analog`" or a "`digital`" action. Here is how you find out which listener is the right one for which type of input.
  201. Mappings registered to the *AnalogListener* are triggered repeatedly and gradually.
  202. * Parameters:
  203. .. JME gives you access to the name of the triggered action.
  204. .. JME gives you access to a gradual value showing the strength of that input. In the case of a keypress that will be the tpf value for which it was pressed since the last frame. For other inputs such as a joystick which give analogue control though then the value will also indicate the strength of the input premultiplied by tpf. For an example on this go to xref:beginner/hello_input_system/timekeypressed.adoc[jMonkeyEngine 3 Tutorial (5) - Hello Input System - Variation over time key is pressed].
  205. In order to see the total time that a key has been pressed for then the incoming value can be accumulated. The analogue listener may also need to be combined with an action listener so that you are notified when the key is released.
  206. * Example: Navigational events (e.g. Left, Right, Rotate, Run, Strafe), situations where you interact continuously.
  207. Mappings registered to the *ActionListener* are digital either-or actions – "`Pressed`" or "`Peleased`"? "`On`" or "`Off`"?
  208. * Parameters:
  209. .. JME gives you access to the name of the triggered action.
  210. .. JME gives you access to a boolean whether the key is pressed or not.
  211. * Example: Pause button, shooting, selecting, jumping, one-time click interactions.
  212. [TIP]
  213. ====
  214. 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:
  215. [source,java]
  216. ----
  217. if (name.equals("Pause") && !keyPressed) {
  218. isRunning = !isRunning;
  219. }
  220. ----
  221. ====
  222. == Table of Triggers
  223. 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:
  224. [cols="2", options="header"]
  225. |===
  226. a| Trigger
  227. a| Code
  228. a| Mouse button: Left Click
  229. a| MouseButtonTrigger(MouseInput.BUTTON_LEFT)
  230. a| Mouse button: Right Click
  231. a| MouseButtonTrigger(MouseInput.BUTTON_RIGHT)
  232. a| Keyboard: Characters and Numbers
  233. a| KeyTrigger(KeyInput.KEY_X)
  234. <a| Keyboard: Spacebar
  235. a| KeyTrigger(KeyInput.KEY_SPACE)
  236. a| Keyboard: Return, Enter
  237. <a| KeyTrigger(KeyInput.KEY_RETURN), +
  238. KeyTrigger(KeyInput.KEY_NUMPADENTER)
  239. a| Keyboard: Escape
  240. a| KeyTrigger(KeyInput.KEY_ESCAPE)
  241. a| Keyboard: Arrows
  242. a| KeyTrigger(KeyInput.KEY_UP), +
  243. KeyTrigger(KeyInput.KEY_DOWN) +
  244. KeyTrigger(KeyInput.KEY_LEFT), +
  245. KeyTrigger(KeyInput.KEY_RIGHT)
  246. |===
  247. [TIP]
  248. ====
  249. 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.
  250. ====
  251. == Listening For Joystick Connections
  252. Note: Joystick Connection/Disconnection events are only available in *LWJGL3*.
  253. If your game requires handling the addition and removal of new joystick devices you can subscribe to a joystick connection listener.
  254. This will give you the opportunity to enable joystick movement, pause the game if the joystick is disconnected, change keybindings to mouse/keyboard.
  255. [source, java]
  256. ----
  257. inputManager.addJoystickConnectionListener(new JoystickConnectionListener() {
  258. @Override
  259. public void onConnected(Joystick joystick) {
  260. System.out.println("Joystick connected: " + joystick.getName());
  261. }
  262. @Override
  263. public void onDisconnected(Joystick joystick) {
  264. System.out.println("Joystick Disconnected: " + joystick.getName());
  265. }
  266. });
  267. ----
  268. == Exercises
  269. . Add mappings for moving the player (box) up and down with the H and L keys!
  270. . Modify the mappings so that you can also trigger the up an down motion with the mouse scroll wheel!
  271. +
  272. TIP: Use `new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true)`
  273. . In which situation would it be better to use variables instead of literals for the MouseInput/KeyInput definitions?
  274. +
  275. [source,java]
  276. ----
  277. int usersPauseKey = KeyInput.KEY_P;
  278. ...
  279. inputManager.addMapping("Pause", new KeyTrigger(usersPauseKey));
  280. ----
  281. . Switch off the flyCam and override the WASD keys.
  282. +
  283. TIP: Use xref:tutorials:intermediate/faq.adoc#how-do-i-switch-between-third-person-and-first-person-view[flyCam.setEnabled(false);]
  284. [IMPORTANT]
  285. ====
  286. <<beginner/solutions.adoc#hello-input,Some proposed solutions>> +
  287. *Be sure to try to solve them for yourself first!*
  288. ====
  289. == Conclusion
  290. You are now able to add custom interactions to your game: You know 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.