input_examples.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. .. _doc_input_examples:
  2. Input examples
  3. ==============
  4. Introduction
  5. ------------
  6. In this tutorial, you'll learn how to use Godot's :ref:`InputEvent <class_InputEvent>`
  7. system to capture player input. There are many different types of input your
  8. game may use - keyboard, gamepad, mouse, etc. - and many different ways to
  9. turn those inputs into actions in your game. This document will show you some
  10. of the most common scenarios, which you can use as starting points for your
  11. own projects.
  12. .. note:: For a detailed overview of how Godot's input event system works,
  13. see :ref:`doc_inputevent`.
  14. Events versus polling
  15. ---------------------
  16. Sometimes you want your game to respond to a certain input event - pressing
  17. the "jump" button, for example. For other situations, you might want something
  18. to happen as long as a key is pressed, such as movement. In the first case,
  19. you can use the ``_input()`` function, which will be called whenever an input
  20. event occurs. In the second case, Godot provides the :ref:`Input <class_Input>`
  21. singleton, which you can use to query the state of an input.
  22. Examples:
  23. .. tabs::
  24. .. code-tab:: gdscript GDScript
  25. func _input(event):
  26. if event.is_action_pressed("jump"):
  27. jump()
  28. func _physics_process(delta):
  29. if Input.is_action_pressed("move_right"):
  30. # Move as long as the key/button is pressed.
  31. position.x += speed * delta
  32. .. code-tab:: csharp
  33. public override void _Input(InputEvent inputEvent)
  34. {
  35. if (inputEvent.IsActionPressed("jump"))
  36. {
  37. Jump();
  38. }
  39. }
  40. public override void _PhysicsProcess(float delta)
  41. {
  42. if (Input.IsActionPressed("move_right"))
  43. {
  44. // Move as long as the key/button is pressed.
  45. position.x += speed * delta;
  46. }
  47. }
  48. This gives you the flexibility to mix-and-match the type of input processing
  49. you do.
  50. For the remainder of this tutorial, we'll focus on capturing individual
  51. events in ``_input()``.
  52. Input events
  53. ------------
  54. Input events are objects that inherit from :ref:`InputEvent <class_InputEvent>`.
  55. Depending on the event type, the object will contain specific properties
  56. related to that event. To see what events actually look like, add a Node and
  57. attach the following script:
  58. .. tabs::
  59. .. code-tab:: gdscript GDScript
  60. extends Node
  61. func _input(event):
  62. print(event.as_text())
  63. .. code-tab:: csharp
  64. using Godot;
  65. using System;
  66. public class Node : Godot.Node
  67. {
  68. public override void _Input(InputEvent inputEvent)
  69. {
  70. GD.Print(inputEvent.AsText());
  71. }
  72. }
  73. As you press keys, move the mouse, and perform other inputs, you'll see each
  74. event scroll by in the output window. Here's an example of the output:
  75. ::
  76. A
  77. InputEventMouseMotion : button_mask=0, position=(108, 108), relative=(26, 1), speed=(164.152496, 159.119843), pressure=(0), tilt=(0, 0)
  78. InputEventMouseButton : button_index=BUTTON_LEFT, pressed=true, position=(108, 107), button_mask=1, doubleclick=false
  79. InputEventMouseButton : button_index=BUTTON_LEFT, pressed=false, position=(108, 107), button_mask=0, doubleclick=false
  80. S
  81. F
  82. Alt
  83. InputEventMouseMotion : button_mask=0, position=(108, 107), relative=(0, -1), speed=(164.152496, 159.119843), pressure=(0), tilt=(0, 0)
  84. As you can see, the results are very different for the different types of
  85. input. Key events are even printed as their key symbols. For example, let's
  86. consider :ref:`InputEventMouseButton <class_InputEventMouseButton>`.
  87. It inherits from the following classes:
  88. - :ref:`InputEvent <class_InputEvent>` - the base class for all input events
  89. - :ref:`InputEventWithModifiers <class_InputEventWithModifiers>` - adds the ability to check if modifiers are pressed, such as :kbd:`Shift` or :kbd:`Alt`.
  90. - :ref:`InputEventMouse <class_InputEventMouse>` - adds mouse event properties, such as ``position``
  91. - :ref:`InputEventMouseButton <class_InputEventMouseButton>` - contains the index of the button that was pressed, whether it was a double-click, etc.
  92. .. tip:: It's a good idea to keep the class reference open while you're working
  93. with events so you can check the event type's available properties and
  94. methods.
  95. You can encounter errors if you try to access a property on an input type that
  96. doesn't contain it - calling ``position`` on ``InputEventKey`` for example. To
  97. avoid this, make sure to test the event type first:
  98. .. tabs::
  99. .. code-tab:: gdscript GDScript
  100. func _input(event):
  101. if event is InputEventMouseButton:
  102. print("mouse button event at ", event.position)
  103. .. code-tab:: csharp
  104. public override void _Input(InputEvent inputEvent)
  105. {
  106. if (inputEvent is InputEventMouseButton mouseEvent)
  107. {
  108. GD.Print("mouse button event at ", mouseEvent.Position);
  109. }
  110. }
  111. InputMap
  112. --------
  113. The :ref:`InputMap <class_InputMap>` is the most flexible way to handle a
  114. variety of inputs. You use this by creating named input *actions*, to which
  115. you can assign any number of input events, such as keypresses or mouse clicks.
  116. A new Godot project includes a number of default actions already defined. To
  117. see them, and to add your own, open Project -> Project Settings and select
  118. the InputMap tab:
  119. .. image:: img/inputs_inputmap.png
  120. Capturing actions
  121. ~~~~~~~~~~~~~~~~~
  122. Once you've defined your actions, you can process them in your scripts using
  123. ``is_action_pressed()`` and ``is_action_released()`` by passing the name of
  124. the action you're looking for:
  125. .. tabs::
  126. .. code-tab:: gdscript GDScript
  127. func _input(event):
  128. if event.is_action_pressed("my_action"):
  129. print("my_action occurred!")
  130. .. code-tab:: csharp
  131. public override void _Input(InputEvent inputEvent)
  132. {
  133. if (inputEvent.IsActionPressed("my_action"))
  134. {
  135. GD.Print("my_action occurred!");
  136. }
  137. }
  138. Keyboard events
  139. ---------------
  140. Keyboard events are captured in :ref:`InputEventKey <class_InputEventKey>`.
  141. While it's recommended to use input actions instead, there may be cases where
  142. you want to specifically look at key events. For this example, let's check for
  143. the :kbd:`T`:
  144. .. tabs::
  145. .. code-tab:: gdscript GDScript
  146. func _input(event):
  147. if event is InputEventKey and event.pressed:
  148. if event.scancode == KEY_T:
  149. print("T was pressed")
  150. .. code-tab:: csharp
  151. public override void _Input(InputEvent inputEvent)
  152. {
  153. if (inputEvent is InputEventKey keyEvent && keyEvent.Pressed)
  154. {
  155. if ((KeyList)keyEvent.Keycode == KeyList.T)
  156. {
  157. GD.Print("T was pressed");
  158. }
  159. }
  160. }
  161. .. tip:: See :ref:`@GlobalScope_KeyList <enum_@GlobalScope_KeyList>` for a list of scancode
  162. constants.
  163. .. warning::
  164. Due to *keyboard ghosting*, not all key inputs may be registered at a given time
  165. if you press too many keys at once. Due to their location on the keyboard,
  166. certain keys are more prone to ghosting than others. Some keyboards feature
  167. antighosting at a hardware level, but this feature is generally
  168. not present on low-end keyboards and laptop keyboards.
  169. As a result, it's recommended to use a default keyboard layout that is designed to work well
  170. on a keyboard without antighosting. See
  171. `this Gamedev Stack Exchange question <https://gamedev.stackexchange.com/a/109002>`__
  172. for more information.
  173. Keyboard modifiers
  174. ~~~~~~~~~~~~~~~~~~
  175. Modifier properties are inherited from
  176. :ref:`InputEventWithModifiers <class_InputEventWithModifiers>`. This allows
  177. you to check for modifier combinations using boolean properties. Let's imagine
  178. you want one thing to happen when the :kbd:`T` is pressed, but something
  179. different when it's :kbd:`Shift + T`:
  180. .. tabs::
  181. .. code-tab:: gdscript GDScript
  182. func _input(event):
  183. if event is InputEventKey and event.pressed:
  184. if event.scancode == KEY_T:
  185. if event.shift:
  186. print("Shift+T was pressed")
  187. else:
  188. print("T was pressed")
  189. .. code-tab:: csharp
  190. public override void _Input(InputEvent inputEvent)
  191. {
  192. if (inputEvent is InputEventKey keyEvent && keyEvent.Pressed)
  193. {
  194. switch ((KeyList)keyEvent.Scancode)
  195. {
  196. case KeyList.T:
  197. GD.Print(keyEvent.Shift ? "Shift+T was pressed" : "T was pressed");
  198. break;
  199. }
  200. }
  201. }
  202. .. tip:: See :ref:`@GlobalScope_KeyList <enum_@GlobalScope_KeyList>` for a list of scancode
  203. constants.
  204. Mouse events
  205. ------------
  206. Mouse events stem from the :ref:`InputEventMouse <class_InputEventMouse>` class, and
  207. are separated into two types: :ref:`InputEventMouseButton <class_InputEventMouseButton>`
  208. and :ref:`InputEventMouseMotion <class_InputEventMouseMotion>`. Note that this
  209. means that all mouse events will contain a ``position`` property.
  210. Mouse buttons
  211. ~~~~~~~~~~~~~
  212. Capturing mouse buttons is very similar to handling key events. :ref:`@GlobalScope_ButtonList <enum_@GlobalScope_ButtonList>`
  213. contains a list of ``BUTTON_*`` constants for each possible button, which will
  214. be reported in the event's ``button_index`` property. Note that the scrollwheel
  215. also counts as a button - two buttons, to be precise, with both
  216. ``BUTTON_WHEEL_UP`` and ``BUTTON_WHEEL_DOWN`` being separate events.
  217. .. tabs::
  218. .. code-tab:: gdscript GDScript
  219. func _input(event):
  220. if event is InputEventMouseButton:
  221. if event.button_index == BUTTON_LEFT and event.pressed:
  222. print("Left button was clicked at ", event.position)
  223. if event.button_index == BUTTON_WHEEL_UP and event.pressed:
  224. print("Wheel up")
  225. .. code-tab:: csharp
  226. public override void _Input(InputEvent inputEvent)
  227. {
  228. if (inputEvent is InputEventMouseButton mouseEvent && mouseEvent.Pressed)
  229. {
  230. switch ((ButtonList)mouseEvent.ButtonIndex)
  231. {
  232. case ButtonList.Left:
  233. GD.Print("Left button was clicked at ", {mouseEvent.Position});
  234. break;
  235. case ButtonList.WheelUp:
  236. GD.Print("Wheel up");
  237. break;
  238. }
  239. }
  240. }
  241. Mouse motion
  242. ~~~~~~~~~~~~
  243. :ref:`InputEventMouseMotion <class_InputEventMouseMotion>` events occur whenever
  244. the mouse moves. You can find the move's distance with the ``relative``
  245. property.
  246. Here's an example using mouse events to drag-and-drop a :ref:`Sprite <class_Sprite>`
  247. node:
  248. .. tabs::
  249. .. code-tab:: gdscript GDScript
  250. extends Node
  251. var dragging = false
  252. var click_radius = 32 # Size of the sprite.
  253. func _input(event):
  254. if event is InputEventMouseButton and event.button_index == BUTTON_LEFT:
  255. if (event.position - $Sprite.position).length() < click_radius:
  256. # Start dragging if the click is on the sprite.
  257. if not dragging and event.pressed:
  258. dragging = true
  259. # Stop dragging if the button is released.
  260. if dragging and not event.pressed:
  261. dragging = false
  262. if event is InputEventMouseMotion and dragging:
  263. # While dragging, move the sprite with the mouse.
  264. $Sprite.position = event.position
  265. .. code-tab:: csharp
  266. using Godot;
  267. using System;
  268. public class Node2D : Godot.Node2D
  269. {
  270. private bool dragging = false;
  271. private int clickRadius = 32; // Size of the sprite.
  272. public override void _Input(InputEvent inputEvent)
  273. {
  274. Sprite sprite = GetNodeOrNull<Sprite>("Sprite");
  275. if (sprite == null)
  276. {
  277. return; // No suitable node was found.
  278. }
  279. if (inputEvent is InputEventMouseButton mouseEvent && (ButtonList)mouseEvent.ButtonIndex == ButtonList.Left)
  280. {
  281. if ((mouseEvent.Position - sprite.Position).Length() < clickRadius)
  282. {
  283. // Start dragging if the click is on the sprite.
  284. if (!dragging && mouseEvent.Pressed)
  285. {
  286. dragging = true;
  287. }
  288. }
  289. // Stop dragging if the button is released.
  290. if (dragging && !mouseEvent.Pressed)
  291. {
  292. dragging = false;
  293. }
  294. }
  295. else
  296. {
  297. if (inputEvent is InputEventMouseMotion motionEvent && dragging)
  298. {
  299. // While dragging, move the sprite with the mouse.
  300. sprite.Position = motionEvent.Position;
  301. }
  302. }
  303. }
  304. }
  305. Touch events
  306. ------------
  307. If you are using a touchscreen device, you can generate touch events.
  308. :ref:`InputEventScreenTouch <class_InputEventScreenTouch>` is equivalent to
  309. a mouse click event, and :ref:`InputEventScreenDrag <class_InputEventScreenDrag>`
  310. works much the same as mouse motion.
  311. .. tip:: To test your touch events on a non-touchscreen device, open Project
  312. Settings and go to the "Input Devices/Pointing" section. Enable "Emulate
  313. Touch From Mouse" and your project will interpret mouse clicks and
  314. motion as touch events.