signals.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. .. Intention: give the user a first taste of signals. We should write more
  2. documentation in the scripting/ section.
  3. .. Note: GDScript snippets use one line return instead of two because they're
  4. really short.
  5. .. meta::
  6. :keywords: Signal
  7. .. _doc_signals:
  8. Using signals
  9. =============
  10. In this lesson, we will look at signals. They are messages that nodes emit when
  11. something specific happens to them, like a button being pressed. Other nodes can
  12. connect to that signal and call a function when the event occurs.
  13. Signals are a delegation mechanism built into Godot that allows one game object to
  14. react to a change in another without them referencing one another. Using signals
  15. limits `coupling
  16. <https://en.wikipedia.org/wiki/Coupling_(computer_programming)>`_ and keeps your
  17. code flexible.
  18. For example, you might have a life bar on the screen that represents the
  19. player’s health. When the player takes damage or uses a healing potion, you want
  20. the bar to reflect the change. To do so, in Godot, you would use signals.
  21. .. note:: As mentioned in the introduction, signals are Godot's version of the
  22. observer pattern. You can learn more about it here:
  23. https://gameprogrammingpatterns.com/observer.html
  24. We will now use a signal to make our Godot icon from the previous lesson
  25. (:ref:`doc_scripting_player_input`) move and stop by pressing a button.
  26. .. Example
  27. Scene setup
  28. -----------
  29. To add a button to our game, we will create a new main scene which will include
  30. both a button and the ``Sprite2D.tscn`` scene that we scripted in previous
  31. lessons.
  32. Create a new scene by going to the menu Scene -> New Scene.
  33. .. image:: img/signals_01_new_scene.png
  34. In the Scene dock, click the 2D Scene button. This will add a Node2D as our
  35. root.
  36. .. image:: img/signals_02_2d_scene.png
  37. In the FileSystem dock, click and drag the ``Sprite2D.tscn`` file you saved
  38. previously onto the Node2D to instantiate it.
  39. .. image:: img/signals_03_dragging_scene.png
  40. We want to add another node as a sibling of the Sprite2D. To do so, right-click
  41. on Node2D and select Add Child Node.
  42. .. image:: img/signals_04_add_child_node.png
  43. Search for the Button node type and add it.
  44. .. image:: img/signals_05_add_button.png
  45. The node is small by default. Click and drag on the bottom-right handle of the
  46. Button in the viewport to resize it.
  47. .. image:: img/signals_06_drag_button.png
  48. If you don't see the handles, ensure the select tool is active in the toolbar.
  49. .. image:: img/signals_07_select_tool.png
  50. Click and drag on the button itself to move it closer to the sprite.
  51. You can also write a label on the Button by editing its Text property in the
  52. Inspector. Enter "Toggle motion".
  53. .. image:: img/signals_08_toggle_motion_text.png
  54. Your scene tree and viewport should look like this.
  55. .. image:: img/signals_09_scene_setup.png
  56. Save your newly created scene. You can then run it with :kbd:`F6` (:kbd:`Cmd + R` on macOS).
  57. At the moment, the button will be visible, but nothing will happen if you
  58. press it.
  59. Connecting a signal in the editor
  60. ---------------------------------
  61. Here, we want to connect the Button's "pressed" signal to our Sprite2D, and we
  62. want to call a new function that will toggle its motion on and off. We need to
  63. have a script attached to the Sprite2D node, which we do from the previous
  64. lesson.
  65. You can connect signals in the Node dock. Select the Button node and, on the
  66. right side of the editor, click on the tab named "Node" next to the Inspector.
  67. .. image:: img/signals_10_node_dock.png
  68. The dock displays a list of signals available on the selected node.
  69. .. image:: img/signals_11_pressed_signals.png
  70. Double-click the "pressed" signal to open the node connection window.
  71. .. image:: img/signals_12_node_connection.png
  72. There, you can connect the signal to the Sprite2D node. The node needs a
  73. receiver method, a function that Godot will call when the Button emits the
  74. signal. The editor generates one for you. By convention, we name these callback
  75. methods "_on_NodeName_signal_name". Here, it'll be "_on_Button_pressed".
  76. .. note::
  77. When connecting signals via the editor's Node dock, you can use two
  78. modes. The simple one only allows you to connect to nodes that have a
  79. script attached to them and creates a new callback function on them.
  80. .. image:: img/signals_advanced_connection_window.png
  81. The advanced view lets you connect to any node and any built-in
  82. function, add arguments to the callback, and set options. You can
  83. toggle the mode in the window's bottom-right by clicking the Advanced
  84. button.
  85. Click the Connect button to complete the signal connection and jump to the
  86. Script workspace. You should see the new method with a connection icon in the
  87. left margin.
  88. .. image:: img/signals_13_signals_connection_icon.png
  89. If you click the icon, a window pops up and displays information about the
  90. connection. This feature is only available when connecting nodes in the editor.
  91. .. image:: img/signals_14_signals_connection_info.png
  92. Let's replace the line with the ``pass`` keyword with code that'll toggle the
  93. node's motion.
  94. Our Sprite2D moves thanks to code in the ``_process()`` function. Godot provides
  95. a method to toggle processing on and off: :ref:`Node.set_process()
  96. <class_Node_method_set_process>`. Another method of the Node class,
  97. ``is_processing()``, returns ``true`` if idle processing is active. We can use
  98. the ``not`` keyword to invert the value.
  99. .. tabs::
  100. .. code-tab:: gdscript GDScript
  101. func _on_Button_pressed():
  102. set_process(not is_processing())
  103. .. code-tab:: csharp C#
  104. public void OnButtonPressed()
  105. {
  106. SetProcess(!IsProcessing());
  107. }
  108. This function will toggle processing and, in turn, the icon's motion on and off
  109. upon pressing the button.
  110. Before trying the game, we need to simplify our ``_process()`` function to move
  111. the node automatically and not wait for user input. Replace it with the
  112. following code, which we saw two lessons ago:
  113. .. tabs::
  114. .. code-tab:: gdscript GDScript
  115. func _process(delta):
  116. rotation += angular_speed * delta
  117. var velocity = Vector2.UP.rotated(rotation) * speed
  118. position += velocity * delta
  119. .. code-tab:: csharp C#
  120. public override void _Process(float delta)
  121. {
  122. Rotation += AngularSpeed * delta;
  123. var velocity = Vector2.Up.Rotated(Rotation) * Speed;
  124. Position += velocity * delta;
  125. }
  126. Your complete ``Sprite2D.gd`` code should look like the following.
  127. .. tabs::
  128. .. code-tab:: gdscript GDScript
  129. extends Sprite2D
  130. var speed = 400
  131. var angular_speed = PI
  132. func _process(delta):
  133. rotation += angular_speed * delta
  134. var velocity = Vector2.UP.rotated(rotation) * speed
  135. position += velocity * delta
  136. func _on_Button_pressed():
  137. set_process(not is_processing())
  138. .. code-tab:: csharp C#
  139. using Godot;
  140. public class Sprite : Godot.Sprite2D
  141. {
  142. private float Speed = 400;
  143. private float AngularSpeed = Mathf.Pi;
  144. public override void _Process(float delta)
  145. {
  146. Rotation += AngularSpeed * delta;
  147. var velocity = Vector2.Up.Rotated(Rotation) * Speed;
  148. Position += velocity * delta;
  149. }
  150. public void OnButtonPressed()
  151. {
  152. SetProcess(!IsProcessing());
  153. }
  154. }
  155. Run the scene now and click the button to see the sprite start and stop.
  156. Connecting a signal via code
  157. ----------------------------
  158. You can connect signals via code instead of using the editor. This is necessary
  159. when you create nodes or instantiate scenes inside of a script.
  160. Let's use a different node here. Godot has a :ref:`Timer <class_Timer>` node
  161. that's useful to implement skill cooldown times, weapon reloading, and more.
  162. Head back to the 2D workspace. You can either click the "2D" text at the top of
  163. the window or press :kbd:`Ctrl + F1` (:kbd:`Alt + 1` on macOS).
  164. In the Scene dock, right-click on the Sprite2D node and add a new child node.
  165. Search for Timer and add the corresponding node. Your scene should now look like
  166. this.
  167. .. image:: img/signals_15_scene_tree.png
  168. With the Timer node selected, go to the Inspector and check the **Autostart**
  169. property.
  170. .. image:: img/signals_18_timer_autostart.png
  171. Click the script icon next to Sprite2D to jump back to the scripting workspace.
  172. .. image:: img/signals_16_click_script.png
  173. We need to do two operations to connect the nodes via code:
  174. 1. Get a reference to the Timer from the Sprite2D.
  175. 2. Call the Timer's ``connect()`` method.
  176. .. note:: To connect to a signal via code, you need to call the ``connect()``
  177. method of the node you want to listen to. In this case, we want to
  178. listen to the Timer's "timeout" signal.
  179. We want to connect the signal when the scene is instantiated, and we can do that
  180. using the :ref:`Node._ready() <class_Node_method__ready>` built-in function,
  181. which is called automatically by the engine when a node is fully instantiated.
  182. To get a reference to a node relative to the current one, we use the method
  183. :ref:`Node.get_node() <class_Node_method_get_node>`. We can store the reference
  184. in a variable.
  185. .. tabs::
  186. .. code-tab:: gdscript GDScript
  187. func _ready():
  188. var timer = get_node("Timer")
  189. .. code-tab:: csharp C#
  190. public override void _Ready()
  191. {
  192. var timer = GetNode<Timer>("Timer");
  193. }
  194. The function ``get_node()`` looks at the Sprite2D's children and gets nodes by
  195. their name. For example, if you renamed the Timer node to "BlinkingTimer" in the
  196. editor, you would have to change the call to ``get_node("BlinkingTimer")``.
  197. .. add seealso to a page that explains node features.
  198. We can now connect the Timer to the Sprite2D in the ``_ready()`` function.
  199. .. tabs::
  200. .. code-tab:: gdscript GDScript
  201. func _ready():
  202. var timer = get_node("Timer")
  203. timer.timeout.connect(_on_Timer_timeout)
  204. .. code-tab:: csharp C#
  205. public override void _Ready()
  206. {
  207. var timer = GetNode<Timer>("Timer");
  208. timer.Connect("timeout", this, nameof(OnTimerTimeout));
  209. }
  210. The line reads like so: we connect the Timer's "timeout" signal to the node to
  211. which the script is attached. When the Timer emits ``timeout``, we want to call
  212. the function ``_on_Timer_timeout()``, that we need to define. Let's add it at the
  213. bottom of our script and use it to toggle our sprite's visibility.
  214. .. tabs::
  215. .. code-tab:: gdscript GDScript
  216. func _on_Timer_timeout():
  217. visible = not visible
  218. .. code-tab:: csharp C#
  219. public void OnTimerTimeout()
  220. {
  221. Visible = !Visible;
  222. }
  223. The ``visible`` property is a boolean that controls the visibility of our node.
  224. The line ``visible = not visible`` toggles the value. If ``visible`` is
  225. ``true``, it becomes ``false``, and vice-versa.
  226. If you run the scene now, you will see that the sprite blinks on and off, at one
  227. second intervals.
  228. Complete script
  229. ---------------
  230. That's it for our little moving and blinking Godot icon demo!
  231. Here is the complete ``Sprite2D.gd`` file for reference.
  232. .. tabs::
  233. .. code-tab:: gdscript GDScript
  234. extends Sprite2D
  235. var speed = 400
  236. var angular_speed = PI
  237. func _ready():
  238. var timer = get_node("Timer")
  239. timer.connect("timeout", self, "_on_Timer_timeout")
  240. func _process(delta):
  241. rotation += angular_speed * delta
  242. var velocity = Vector2.UP.rotated(rotation) * speed
  243. position += velocity * delta
  244. func _on_Button_pressed():
  245. set_process(not is_processing())
  246. func _on_Timer_timeout():
  247. visible = not visible
  248. .. code-tab:: csharp C#
  249. using Godot;
  250. public class Sprite : Godot.Sprite2D
  251. {
  252. private float Speed = 400;
  253. private float AngularSpeed = Mathf.Pi;
  254. public override void _Ready()
  255. {
  256. var timer = GetNode<Timer>("Timer");
  257. timer.Connect("timeout", this, nameof(OnTimerTimeout));
  258. }
  259. public override void _Process(float delta)
  260. {
  261. Rotation += AngularSpeed * delta;
  262. var velocity = Vector2.Up.Rotated(Rotation) * Speed;
  263. Position += velocity * delta;
  264. }
  265. public void OnButtonPressed()
  266. {
  267. SetProcess(!IsProcessing());
  268. }
  269. public void OnTimerTimeout()
  270. {
  271. Visible = !Visible;
  272. }
  273. }
  274. Custom signals
  275. --------------
  276. .. note:: This section is a reference on how to define and use your own signals,
  277. and does not build upon the project created in previous lessons.
  278. You can define custom signals in a script. Say, for example, that you want to
  279. show a game over screen when the player's health reaches zero. To do so, you
  280. could define a signal named "died" or "health_depleted" when their health
  281. reaches 0.
  282. .. tabs::
  283. .. code-tab:: gdscript GDScript
  284. extends Node2D
  285. signal health_depleted
  286. var health = 10
  287. .. code-tab:: csharp C#
  288. using Godot;
  289. public class CustomSignal : Node2D
  290. {
  291. [Signal]
  292. public delegate void HealthDepleted();
  293. private int Health = 10;
  294. }
  295. .. note:: As signals represent events that just occurred, we generally use an
  296. action verb in the past tense in their names.
  297. Your signals work the same way as built-in ones: they appear in the Node tab and
  298. you can connect to them like any other.
  299. .. image:: img/signals_17_custom_signal.png
  300. To emit a signal in your scripts, call ``emit_signal()``.
  301. .. tabs::
  302. .. code-tab:: gdscript GDScript
  303. func take_damage(amount):
  304. health -= amount
  305. if health <= 0:
  306. emit_signal("health_depleted")
  307. .. code-tab:: csharp C#
  308. public void TakeDamage(int amount)
  309. {
  310. Health -= amount;
  311. if (Health < 0)
  312. {
  313. EmitSignal(nameof(HealthDepleted));
  314. }
  315. }
  316. A signal can optionally declare one or more arguments. Specify the argument
  317. names between parentheses:
  318. .. tabs::
  319. .. code-tab:: gdscript GDScript
  320. extends Node
  321. signal health_changed(old_value, new_value)
  322. var health = 10
  323. .. code-tab:: csharp C#
  324. using Godot;
  325. public class CustomSignal : Node
  326. {
  327. [Signal]
  328. public delegate void HealthChanged(int oldValue, int newValue);
  329. private int Health = 10;
  330. }
  331. .. note::
  332. The signal arguments show up in the editor's node dock, and Godot can use
  333. them to generate callback functions for you. However, you can still emit any
  334. number of arguments when you emit signals. So it's up to you to emit the
  335. correct values.
  336. To emit values along with the signal, add them as extra arguments to the
  337. ``emit_signal()`` function:
  338. .. tabs::
  339. .. code-tab:: gdscript GDScript
  340. func take_damage(amount):
  341. var old_health = health
  342. health -= amount
  343. emit_signal("health_changed", old_health, health)
  344. .. code-tab:: csharp C#
  345. public void TakeDamage(int amount)
  346. {
  347. var oldHealth = Health;
  348. Health -= amount;
  349. EmitSignal(nameof(HealthChanged), oldHealth, Health);
  350. }
  351. Summary
  352. -------
  353. Any node in Godot emits signals when something specific happens to them, like a
  354. button being pressed. Other nodes can connect to individual signals and react to
  355. selected events.
  356. Signals have many uses. With them, you can react to a node entering or exiting
  357. the game world, to a collision, to a character entering or leaving an area, to
  358. an element of the interface changing size, and much more.
  359. For example, an :ref:`Area2D <class_Area2D>` representing a coin emits a
  360. ``body_entered`` signal whenever the player's physics body enters its collision
  361. shape, allowing you to know when the player collected it.
  362. In the next section, :ref:`doc_your_first_2d_game`, you'll create a complete 2D
  363. game and put everything you learned so far into practice.