input_handling.adoc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. = Input Handling
  2. :revnumber: 2.0
  3. :revdate: 2020/07/15
  4. :keywords: keyinput, input, documentation
  5. Users interact with your jME3 application with different input devices – the mouse, the keyboard, or a joystick. To respond to inputs we use the `inputManager` object in `SimpleApplication`.
  6. This is how you add interaction to your game:
  7. . For each action, choose the trigger(s) (a key or mouse click etc)
  8. . For each action, add a trigger mapping to the inputManager
  9. . Create at least one listener in SimpleApplication
  10. . For each action, register its mappings to a listener
  11. . Implement each action in the listener
  12. == Code Samples
  13. * link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-examples/src/main/java/jme3test/input/TestControls.java[TestControls.java]
  14. * link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-examples/src/main/java/jme3test/input/TestJoystick.java[TestJoystick.java]
  15. == 1. Choose Trigger
  16. Choose one or several key/mouse events for the interaction. We use `KeyTrigger`, `MouseAxisTrigger`, `MouseButtonTrigger`, `JoyAxisTrigger` and `JoyButtonTrigger` constants from the `com.jme3.input.controls` package.
  17. [NOTE]
  18. ====
  19. The MouseAxis and JoyAxis triggers go along the X axis (right/left) or Y axis (up/down). These Triggers come with extra booleans for the negative half of the axis (left, down). Remember to write code that listens to the negative (true) and positive (false) axis!
  20. ====
  21. [cols="2", options="header"]
  22. |===
  23. a| Trigger
  24. a| Code
  25. a| Mouse button: Left Click
  26. a| MouseButtonTrigger(MouseInput.BUTTON_LEFT)
  27. a| Mouse button: Right Click
  28. a| MouseButtonTrigger(MouseInput.BUTTON_RIGHT)
  29. a| Mouse button: Middle Click
  30. a| MouseButtonTrigger(MouseInput.BUTTON_MIDDLE)
  31. a| Mouse movement: Right
  32. a| MouseAxisTrigger(MouseInput.AXIS_X, true)
  33. a| Mouse movement: Left
  34. a| MouseAxisTrigger(MouseInput.AXIS_X, false)
  35. a| Mouse movement: Up
  36. a| MouseAxisTrigger(MouseInput.AXIS_Y, true)
  37. a| Mouse movement: Down
  38. a| MouseAxisTrigger(MouseInput.AXIS_Y, false)
  39. a| Mouse wheel: Up
  40. a| MouseAxisTrigger(MouseInput.AXIS_WHEEL,false)
  41. a| Mouse wheel: Down
  42. a| MouseAxisTrigger(MouseInput.AXIS_WHEEL,true)
  43. a| NumPad: 1, 2, 3, …
  44. a| KeyTrigger(KeyInput.KEY_NUMPAD1) …
  45. a| Keyboard: 1, 2 , 3, …
  46. a| KeyTrigger(KeyInput.KEY_1) …
  47. a| Keyboard: A, B, C, …
  48. a| KeyTrigger(KeyInput.KEY_A) …
  49. a| Keyboard: Spacebar
  50. a| KeyTrigger(KeyInput.KEY_SPACE)
  51. a| Keyboard: Shift
  52. a| KeyTrigger(KeyInput.KEY_RSHIFT), +
  53. KeyTrigger(KeyInput.KEY_LSHIFT)
  54. a| Keyboard: F1, F2, …
  55. a| KeyTrigger(KeyInput.KEY_F1) …
  56. a| Keyboard: Return, Enter
  57. <a| KeyTrigger(KeyInput.KEY_RETURN), +
  58. KeyTrigger(KeyInput.KEY_NUMPADENTER)
  59. a| Keyboard: PageUp, PageDown
  60. a| KeyTrigger(KeyInput.KEY_PGUP), +
  61. KeyTrigger(KeyInput.KEY_PGDN)
  62. a| Keyboard: Delete, Backspace
  63. a| KeyTrigger(KeyInput.KEY_BACK), +
  64. KeyTrigger(KeyInput.KEY_DELETE)
  65. a| Keyboard: Escape
  66. a| KeyTrigger(KeyInput.KEY_ESCAPE)
  67. a| Keyboard: Arrows
  68. a| KeyTrigger(KeyInput.KEY_DOWN), +
  69. KeyTrigger(KeyInput.KEY_UP) +
  70. KeyTrigger(KeyInput.KEY_LEFT), KeyTrigger(KeyInput.KEY_RIGHT)
  71. a| Joystick Button:
  72. a| JoyButtonTrigger(0, JoyInput.AXIS_POV_X), +
  73. JoyButtonTrigger(0, JoyInput.AXIS_POV_Y) ?
  74. a| Joystick Movement: Right
  75. a| JoyAxisTrigger(0, JoyInput.AXIS_POV_X, true)
  76. a| Joystick Movement: Left
  77. a| JoyAxisTrigger(0, JoyInput.AXIS_POV_X, false)
  78. a| Joystick Movement: Forward
  79. a| JoyAxisTrigger(0, JoyInput.AXIS_POV_Z, true)
  80. a| Joystick Movement: Backward
  81. a| JoyAxisTrigger(0, JoyInput.AXIS_POV_Z, false)
  82. |===
  83. In your IDE, use code completion to quickly look up Trigger literals. In the jMonkeyEngine SDK for example, press ctrl-space or ctrl-/ after `KeyInput.|` to choose from the list of all keys.
  84. == 2. Remove Default Trigger Mappings
  85. [source]
  86. ----
  87. inputManager.deleteMapping( SimpleApplication.INPUT_MAPPING_MEMORY );
  88. ----
  89. [cols="3", options="header"]
  90. |===
  91. a|Default Mapping
  92. a|Key
  93. a|Description
  94. a|INPUT_MAPPING_HIDE_STATS
  95. a|F5
  96. a|Hides the statistics in the bottom left.
  97. a|INPUT_MAPPING_CAMERA_POS
  98. a|KEY_C
  99. a|Prints debug output about the camera.
  100. a|INPUT_MAPPING_MEMORY
  101. a|KEY_M
  102. a|Prints debug output for memory usage.
  103. a|INPUT_MAPPING_EXIT
  104. a|KEY_ESCAPE
  105. a|Closes the application by calling `stop();`. Typically you do not remove this, unless you replace it by another way of quitting gracefully.
  106. |===
  107. == 3. Add Custom Trigger Mapping
  108. When initializing the application, add a Mapping for each Trigger.
  109. Give the mapping a meaningful name. The name should reflect the action, not the button/key (because buttons/keys can change). Here some examples:
  110. [source,java]
  111. ----
  112. inputManager.addMapping("Pause Game", new KeyTrigger(KeyInput.KEY_P));
  113. inputManager.addMapping("Rotate", new KeyTrigger(KeyInput.KEY_SPACE));
  114. ...
  115. ----
  116. There are cases where you may want to provide more then one trigger for one action. For example, some users prefer the WASD keys to navigate, while others prefer the arrow keys. Add several triggers for one mapping, by separating the Trigger objects with commas:
  117. [source,java]
  118. ----
  119. inputManager.addMapping("Left", new KeyTrigger(KeyInput.KEY_A),
  120. new KeyTrigger(KeyInput.KEY_LEFT)); // A and left arrow
  121. inputManager.addMapping("Right", new KeyTrigger(KeyInput.KEY_D),
  122. new KeyTrigger(KeyInput.KEY_RIGHT)); // D and right arrow
  123. ...
  124. ----
  125. == 4. Create Listeners
  126. The jME3 input manager supports two types of event listeners for inputs: AnalogListener and ActionListener. You can use one or both listeners in the same application. Add one or both of the following code snippets to your main SimpleApplication-based class to activate the listeners.
  127. [NOTE]
  128. ====
  129. The two input listeners do not know, and do not care, which actual key was pressed. They only know which _named input mapping_ was triggered.
  130. ====
  131. === ActionListener
  132. `com.jme3.input.controls.ActionListener`
  133. * Use for absolute "`button`" pressed or released?, on or off? actions.
  134. ** Examples: Pause/unpause, a rifle or revolver shot, jump, click to select.
  135. * JME gives you access to:
  136. ** The mapping name of the triggered action.
  137. ** A boolean whether the trigger is still pressed or has just been released.
  138. ** A float of the current time-per-frame as timing factor
  139. [source,java]
  140. ----
  141. private ActionListener actionListener = new ActionListener() {
  142. public void onAction(String name, boolean keyPressed, float tpf) {
  143. /** TODO: test for mapping names and implement actions */
  144. }
  145. };
  146. ----
  147. === AnalogListener
  148. `com.jme3.input.controls.AnalogListener`
  149. * Use for continuous and gradual actions.
  150. ** Examples: Walk, run, rotate, accelerate vehicle, strafe, (semi-)automatic weapon shot
  151. * JME gives you access to:
  152. ** The mapping name of the triggered action.
  153. ** A gradual float value between how long the trigger has been pressed.
  154. ** A float of the current time-per-frame as timing factor
  155. [source,java]
  156. ----
  157. private AnalogListener analogListener = new AnalogListener() {
  158. public void onAnalog(String name, float keyPressed, float tpf) {
  159. /** TODO: test for mapping names and implement actions */
  160. }
  161. };
  162. ----
  163. == 4. Register Mappings to Listeners
  164. To activate the mappings, you must register them to a Listener. Write your registration code after the code block where you have added the mappings to the inputManager.
  165. In the following example, you register the "`Pause Game`" mapping to the `actionListener` object, because pausing a game is in "`either/or`" decision.
  166. [source,java]
  167. ----
  168. inputManager.addListener(actionListener, new String[]{"Pause Game"});
  169. ----
  170. In the following example, you register navigational mappings to the `analogListener` object, because walking is a continuous action. Players typically keep the key pressed to express continuity, for example when they want to "`walk`" on or "`accelerate`".
  171. [source,java]
  172. ----
  173. inputManager.addListener(analogListener, new String[]{"Left", "Right"});
  174. ----
  175. As you see, you can add several listeners in one String array. You can call the addListener() method more than once, each time with a subset of your list, if that helps you keep you code tidy. Again, the Listeners do not care about actual which keys are configured, you only register named trigger mappings.
  176. [TIP]
  177. ====
  178. Did you register an action, but it does not work? Check the string's capitalization and spelling, it's case sensitive!
  179. ====
  180. == 5. Implement Actions in Listeners
  181. You specify the action to be triggered where it says TODO in the Listener code snippets. Typically, you write a series of if/else conditions, testing for all the mapping names, and then calling the respective action.
  182. Make use of the distinction between `if` and `else if` in this conditional.
  183. * If several actions can be triggered simultaneously, test for all of these with a series of bare `if`s. For example, a character can be running forward _and_ to the left.
  184. * If certain actions exclude one another, test for them with `else if`, the the rest of the exclusive tests can be skipped and you save some milliseconds. For example, you either shoot or pick something up.
  185. === ActionListener
  186. In the most common case, you want an action to be triggered once, in the moment when the button or key trigger is released. For example, when the player presses a key to open a door, or clicks to pick up an item. For these cases, use an ActionListener and test for `&amp;&amp; !keyPressed`, like shown in the following example.
  187. [source,java]
  188. ----
  189. private ActionListener actionListener = new ActionListener() {
  190. public void onAction(String name, boolean keyPressed, float tpf) {
  191. if (name.equals("Pause Game") && !keyPressed) { // test?
  192. isRunning = !isRunning; // action!
  193. }
  194. if ...
  195. }
  196. };
  197. ----
  198. === AnalogListener
  199. The following example shows how you define actions with an AnalogListener. These actions are triggered continuously, as long (intensity `value`) as the named key or mouse button is down. Use this listeners for semi-automatic weapons and navigational actions.
  200. [source,java]
  201. ----
  202. private AnalogListener analogListener = new AnalogListener() {
  203. public void onAnalog(String name, float value, float tpf) {
  204. if (name.equals("Rotate")) { // test?
  205. player.rotate(0, value*speed, 0); // action!
  206. }
  207. if ...
  208. }
  209. };
  210. ----
  211. == Let Users Remap Keys
  212. It is likely that your players have different keyboard layouts, are used to "`reversed`" mouse navigation, or prefer different navigational keys than the ones that you defined. You should create an options screen that lets users customize their mouse/key triggers for your mappings. Replace the trigger literals in the `inputManager.addMapping()` lines with variables, and load sets of triggers when the game starts.
  213. The abstraction of separating triggers and mappings has the advantage that you can remap triggers easily. Your code only needs to remove and add some trigger mappings. The core of the code (the listeners and actions) remains unchanged.
  214. == Detecting Joystick Connection States
  215. For information regarding the connection state of a joystick see <<tutorials:beginner/hello_input_system.adoc#listening-for-joystick-connections,Listening for Joystick Connections>>.