signals.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. .. _doc_signals:
  2. Signals
  3. =======
  4. Introduction
  5. ------------
  6. Signals are Godot's version of the *observer* pattern. They allow a node to
  7. send out a message that other nodes can listen for and respond to. For example,
  8. rather than continuously checking a button to see if it's being pressed, the
  9. button can emit a signal when it's pressed.
  10. .. note:: You can read more about the observer pattern here: http://gameprogrammingpatterns.com/observer.html
  11. Signals are a way to *decouple* your game objects, which leads to better organized
  12. and more manageable code. Instead of forcing game objects to expect other objects
  13. to always be present, they can instead emit signals that all interested objects can
  14. subscribe to and respond to.
  15. Below you can see some examples of how you can use signals in your own projects.
  16. Timer example
  17. -------------
  18. To see how signals work, let's try using a :ref:`Timer <class_Timer>` node. Create
  19. a new scene with a Node and two children: a Timer and a :ref:`Sprite <class_Sprite>`.
  20. In the Scene dock, rename Node to TimerExample.
  21. For the Sprite's texture, you can use the Godot icon, or any other image you
  22. like. Do so by selecting ``Load`` in the Sprite's Texture attribute drop-down menu.
  23. Attach a script to the root node, but don't add any code to it yet.
  24. Your scene tree should look like this:
  25. .. image:: img/signals_node_setup.png
  26. In the Timer node's properties, check the "On" box next to *Autostart*. This will
  27. cause the timer to start automatically when you run the scene. You can leave the
  28. *Wait Time* at 1 second.
  29. Next to the "Inspector" tab is a tab labeled "Node". Click on this tab and you'll
  30. see all of the signals that the selected node can emit. In the case of the Timer
  31. node, the one we're concerned with is "timeout". This signal is emitted whenever
  32. the Timer reaches ``0``.
  33. .. image:: img/signals_node_tab_timer.png
  34. Click on the "timeout()" signal and click "Connect...". You'll see the following
  35. window, where you can define how you want to connect the signal:
  36. .. image:: img/signals_connect_dialog_timer.png
  37. On the left side, you'll see the nodes in your scene and can select the node that
  38. you want to "listen" for the signal. Note that the Timer node is red - this is
  39. *not* an error, but is a visual indication that it's the node that is emitting
  40. the signal. Select the root node.
  41. .. warning:: The target node *must* have a script attached or you'll receive
  42. an error message.
  43. On the bottom of the window is a field labeled "Method In Node". This is the name
  44. of the function in the target node's script that you want to use. By default,
  45. Godot will create this function using the naming convention ``_on_<node_name>_<signal_name>``
  46. but you can change it if you wish.
  47. Click "Connect" and you'll see that the function has been created in the script:
  48. .. tabs::
  49. .. code-tab:: gdscript GDScript
  50. extends Node
  51. func _on_Timer_timeout():
  52. pass # replace with function body
  53. .. code-tab:: csharp
  54. public class TimerExample : Node
  55. {
  56. private void _on_Timer_timeout()
  57. {
  58. // Replace with function body.
  59. }
  60. }
  61. Now we can replace the placeholder code with whatever code we want to run when
  62. the signal is received. Let's make the Sprite blink:
  63. .. tabs::
  64. .. code-tab:: gdscript GDScript
  65. extends Node
  66. func _on_Timer_timeout():
  67. $Sprite.visible = !$Sprite.visible
  68. .. code-tab:: csharp
  69. public class TimerExample : Node
  70. {
  71. public void _on_Timer_timeout()
  72. {
  73. var sprite = GetNode<Sprite>("Sprite");
  74. sprite.Visible = !sprite.Visible;
  75. }
  76. }
  77. Run the scene and you'll see the Sprite blinking on and off every second. You can
  78. change the Timer's *Wait Time* property to alter this.
  79. Connecting signals in code
  80. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  81. You can also make the signal connection in code rather than with the editor. This
  82. is usually necessary when you're instancing nodes via code and so you can't use
  83. the editor to make the connection.
  84. First, disconnect the signal by selecting the connection in the Timer's "Node"
  85. tab and clicking disconnect.
  86. .. image:: img/signals_disconnect_timer.png
  87. To make the connection in code, we can use the ``connect`` function. We'll put it
  88. in ``_ready()`` so that the connection will be made on run. The syntax of the
  89. function is ``<source_node>.connect(<signal_name>, <target_node>, <target_function_name>)``.
  90. Here is the code for our Timer connection:
  91. .. tabs::
  92. .. code-tab:: gdscript GDScript
  93. extends Node
  94. func _ready():
  95. $Timer.connect("timeout", self, "_on_Timer_timeout")
  96. func _on_Timer_timeout():
  97. $Sprite.visible = !$Sprite.visible
  98. .. code-tab:: csharp
  99. public class TimerExample : Node
  100. {
  101. public override void _Ready()
  102. {
  103. GetNode("Timer").Connect("timeout", this, nameof(_on_Timer_timeout));
  104. }
  105. public void _on_Timer_timeout()
  106. {
  107. var sprite = GetNode<Sprite>("Sprite");
  108. sprite.Visible = !sprite.Visible;
  109. }
  110. }
  111. Custom signals
  112. --------------
  113. You can also declare your own custom signals in Godot:
  114. .. tabs::
  115. .. code-tab:: gdscript GDScript
  116. extends Node
  117. signal my_signal
  118. .. code-tab:: csharp
  119. public class Main : Node
  120. {
  121. [Signal]
  122. public delegate void MySignal();
  123. }
  124. Once declared, your custom signals will appear in the Inspector and can be connected
  125. in the same way as a node's built-in signals.
  126. To emit a signal via code, use the ``emit`` function:
  127. .. tabs::
  128. .. code-tab:: gdscript GDScript
  129. extends Node
  130. signal my_signal
  131. func _ready():
  132. emit_signal("my_signal")
  133. .. code-tab:: csharp
  134. public class Main : Node
  135. {
  136. [Signal]
  137. public delegate void MySignal();
  138. public override void _Ready()
  139. {
  140. EmitSignal(nameof(MySignal));
  141. }
  142. }
  143. Shooting example
  144. ----------------
  145. As another example of signal usage, let's consider a player character that can
  146. rotate and shoot towards the mouse. Every time the mouse button is clicked,
  147. we create an instance of the bullet at the player's location. See :ref:`doc_instancing`
  148. for details.
  149. However, if the bullets are added as children of the player, then they will
  150. remain "attached" to the player as it rotates:
  151. .. image:: img/signals_shoot1.gif
  152. Instead, we need the bullets to be independent of the player's movement - once
  153. fired, they should continue traveling in a straight line and the player can no
  154. longer affect them. Instead of being added to the scene tree as a child of the
  155. player, it makes more sense to add the bullet as a child of the "main" game
  156. scene, which may be the player's parent or even further up the tree.
  157. You could do this by adding the bullet directly:
  158. .. tabs::
  159. .. code-tab:: gdscript GDScript
  160. var bullet_instance = Bullet.instance()
  161. get_parent().add_child(bullet_instance)
  162. .. code-tab:: csharp
  163. Node bulletInstance = Bullet.Instance();
  164. GetParent().AddChild(bulletInstance);
  165. However, this will lead to a different problem. Now if you try and test your
  166. "Player" scene independently, it will crash on shooting, because there is no
  167. parent node to access. This makes it a lot harder to test your player code
  168. independently and also means that if you decide to change your main scene's
  169. node structure, the player's parent may no longer be the appropriate node to
  170. receive the bullets.
  171. The solution to this is to use a signal to "emit" the bullets from the player.
  172. The player then has no need to "know" what happens to the bullets after that -
  173. whatever node is connected to the signal can "receive" the bullets and take the
  174. appropriate action to spawn them.
  175. Here is the code for the player using signals to emit the bullet:
  176. .. tabs::
  177. .. code-tab:: gdscript GDScript
  178. extends Sprite
  179. signal shoot(bullet, direction, location)
  180. var Bullet = preload("res://Bullet.tscn")
  181. func _input(event):
  182. if event is InputEventMouseButton:
  183. if event.button_index == BUTTON_LEFT and event.pressed:
  184. emit_signal("shoot", Bullet, rotation, position)
  185. func _process(delta):
  186. look_at(get_global_mouse_position())
  187. .. code-tab:: csharp
  188. public class Player : Sprite
  189. {
  190. [Signal]
  191. delegate void Shoot(PackedScene bullet, Vector2 direction, Vector2 location);
  192. private PackedScene _bullet = GD.Load<PackedScene>("res://Bullet.tscn");
  193. public override void _Input(InputEvent event)
  194. {
  195. if (input is InputEventMouseButton mouseButton)
  196. {
  197. if (mouseButton.ButtonIndex == (int)ButtonList.Left && mouseButton.Pressed)
  198. {
  199. EmitSignal(nameof(Shoot), _bullet, Rotation, Position);
  200. }
  201. }
  202. }
  203. public override _Process(float delta)
  204. {
  205. LookAt(GetGlobalMousePosition());
  206. }
  207. }
  208. In the main scene, we then connect the player's signal (it will appear in the
  209. "Node" tab).
  210. .. tabs::
  211. .. code-tab:: gdscript GDScript
  212. func _on_Player_shoot(Bullet, direction, location):
  213. var b = Bullet.instance()
  214. add_child(b)
  215. b.rotation = direction
  216. b.position = location
  217. b.velocity = b.velocity.rotated(direction)
  218. .. code-tab:: csharp
  219. public void _on_Player_Shoot(PackedScene bullet, Vector2 direction, Vector2 location)
  220. {
  221. var bulletInstance = (Bullet)bullet.Instance();
  222. AddChild(bulletInstance);
  223. bulletInstance.Rotation = direction;
  224. bulletInstance.Position = location;
  225. bulletInstance.Velocity = bulletInstance.Velocity.Rotated(direction);
  226. }
  227. Now the bullets will maintain their own movement independent of the player's
  228. rotation:
  229. .. image:: img/signals_shoot2.gif
  230. Conclusion
  231. ----------
  232. Many of Godot's built-in node types provide signals you can use to detect
  233. events. For example, an :ref:`Area2D <class_Area2D>` representing a coin emits
  234. a ``body_entered`` signal whenever the player's physics body enters its collision
  235. shape, allowing you to know when the player collected it.
  236. In the next section, :ref:`doc_your_first_game`, you'll build a complete game
  237. including several uses of signals to connect different game components.