instancing_with_signals.rst 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. .. meta::
  2. :keywords: Signal
  3. .. _doc_instancing_with_signals:
  4. Instancing with signals
  5. =======================
  6. Signals provide a way to decouple game objects, allowing you to avoid forcing a
  7. fixed arrangement of nodes. One sign that a signal might be called for is when
  8. you find yourself using ``get_parent()``. Referring directly to a node's parent
  9. means that you can't easily move that node to another location in the scene tree.
  10. This can be especially problematic when you are instancing objects at runtime
  11. and may want to place them in an arbitrary location in the running scene tree.
  12. Below we'll consider an example of such a situation: firing bullets.
  13. Shooting example
  14. ----------------
  15. Consider a player character that can rotate and shoot towards the mouse. Every
  16. time the mouse button is clicked, we create an instance of the bullet at the
  17. player's location. See :ref:`doc_instancing` for details.
  18. We'll use an ``Area2D`` for the bullet, which moves in a straight line at a
  19. given velocity:
  20. .. tabs::
  21. .. code-tab:: gdscript GDScript
  22. extends Area2D
  23. var velocity = Vector2.RIGHT
  24. func _physics_process(delta):
  25. position += velocity * delta
  26. .. code-tab:: csharp
  27. using Godot;
  28. public partial class Bullet : Area2D
  29. {
  30. public Vector2 Velocity { get; set; } = Vector2.Right;
  31. public override void _PhysicsProcess(double delta)
  32. {
  33. Position += Velocity * (float)delta;
  34. }
  35. }
  36. However, if the bullets are added as children of the player, then they will
  37. remain "attached" to the player as it rotates:
  38. .. image:: img/signals_shoot1.gif
  39. Instead, we need the bullets to be independent of the player's movement - once
  40. fired, they should continue traveling in a straight line and the player can no
  41. longer affect them. Instead of being added to the scene tree as a child of the
  42. player, it makes more sense to add the bullet as a child of the "main" game
  43. scene, which may be the player's parent or even further up the tree.
  44. You could do this by adding the bullet to the main scene directly:
  45. .. tabs::
  46. .. code-tab:: gdscript GDScript
  47. var bullet_instance = Bullet.instantiate()
  48. get_parent().add_child(bullet_instance)
  49. .. code-tab:: csharp
  50. Node bulletInstance = Bullet.Instantiate();
  51. GetParent().AddChild(bulletInstance);
  52. However, this will lead to a different problem. Now if you try to test your
  53. "Player" scene independently, it will crash on shooting, because there is no
  54. parent node to access. This makes it a lot harder to test your player code
  55. independently and also means that if you decide to change your main scene's
  56. node structure, the player's parent may no longer be the appropriate node to
  57. receive the bullets.
  58. The solution to this is to use a signal to "emit" the bullets from the player.
  59. The player then has no need to "know" what happens to the bullets after that -
  60. whatever node is connected to the signal can "receive" the bullets and take the
  61. appropriate action to spawn them.
  62. Here is the code for the player using signals to emit the bullet:
  63. .. tabs::
  64. .. code-tab:: gdscript GDScript
  65. extends Sprite2D
  66. signal shoot(bullet, direction, location)
  67. var Bullet = preload("res://bullet.tscn")
  68. func _input(event):
  69. if event is InputEventMouseButton:
  70. if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
  71. shoot.emit(Bullet, rotation, position)
  72. func _process(delta):
  73. look_at(get_global_mouse_position())
  74. .. code-tab:: csharp
  75. using Godot;
  76. public partial class Player : Sprite2D
  77. {
  78. [Signal]
  79. public delegate void ShootEventHandler(PackedScene bullet, float direction, Vector2 location);
  80. private PackedScene _bullet = GD.Load<PackedScene>("res://Bullet.tscn");
  81. public override void _Input(InputEvent @event)
  82. {
  83. if (@event is InputEventMouseButton mouseButton)
  84. {
  85. if (mouseButton.ButtonIndex == MouseButton.Left && mouseButton.Pressed)
  86. {
  87. EmitSignal(SignalName.Shoot, _bullet, Rotation, Position);
  88. }
  89. }
  90. }
  91. public override void _Process(double delta)
  92. {
  93. LookAt(GetGlobalMousePosition());
  94. }
  95. }
  96. In the main scene, we then connect the player's signal (it will appear in the
  97. "Node" tab of the Inspector)
  98. .. tabs::
  99. .. code-tab:: gdscript GDScript
  100. func _on_player_shoot(Bullet, direction, location):
  101. var spawned_bullet = Bullet.instantiate()
  102. add_child(spawned_bullet)
  103. spawned_bullet.rotation = direction
  104. spawned_bullet.position = location
  105. spawned_bullet.velocity = spawned_bullet.velocity.rotated(direction)
  106. .. code-tab:: csharp
  107. private void OnPlayerShoot(PackedScene bullet, float direction, Vector2 location)
  108. {
  109. var spawnedBullet = bullet.Instantiate<Bullet>();
  110. AddChild(spawnedBullet);
  111. spawnedBullet.Rotation = direction;
  112. spawnedBullet.Position = location;
  113. spawnedBullet.Velocity = spawnedBullet.Velocity.Rotated(direction);
  114. }
  115. Now the bullets will maintain their own movement independent of the player's
  116. rotation:
  117. .. image:: img/signals_shoot2.gif