input_examples.rst 13 KB

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