05.the_main_game_scene.rst 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. .. _doc_your_first_2d_game_the_main_game_scene:
  2. The main game scene
  3. ===================
  4. Now it's time to bring everything we did together into a playable game scene.
  5. Create a new scene and add a :ref:`Node <class_Node>` named ``Main``.
  6. (The reason we are using Node instead of Node2D is because this node will
  7. be a container for handling game logic. It does not require 2D functionality itself.)
  8. Click the **Instance** button (represented by a chain link icon) and select your saved
  9. ``player.tscn``.
  10. .. image:: img/instance_scene.webp
  11. Now, add the following nodes as children of ``Main``, and name them as shown:
  12. - :ref:`Timer <class_Timer>` (named ``MobTimer``) - to control how often mobs
  13. spawn
  14. - :ref:`Timer <class_Timer>` (named ``ScoreTimer``) - to increment the score
  15. every second
  16. - :ref:`Timer <class_Timer>` (named ``StartTimer``) - to give a delay before
  17. starting
  18. - :ref:`Marker2D <class_Marker2D>` (named ``StartPosition``) - to indicate
  19. the player's start position
  20. Set the ``Wait Time`` property of each of the ``Timer`` nodes as follows (values are in seconds):
  21. - ``MobTimer``: ``0.5``
  22. - ``ScoreTimer``: ``1``
  23. - ``StartTimer``: ``2``
  24. In addition, set the ``One Shot`` property of ``StartTimer`` to "On" and set
  25. ``Position`` of the ``StartPosition`` node to ``(240, 450)``.
  26. Spawning mobs
  27. ~~~~~~~~~~~~~
  28. The Main node will be spawning new mobs, and we want them to appear at a random
  29. location on the edge of the screen. Add a :ref:`Path2D <class_Path2D>` node
  30. named ``MobPath`` as a child of ``Main``. When you select ``Path2D``, you will
  31. see some new buttons at the top of the editor:
  32. .. image:: img/path2d_buttons.webp
  33. Select the middle one ("Add Point") and draw the path by clicking to add the
  34. points at the corners shown. To have the points snap to the grid, make sure "Use
  35. Grid Snap" and "Use Smart Snap" are both selected. These options can be found to the
  36. left of the "Lock" button, appearing as a magnet next to some dots and
  37. intersecting lines, respectively.
  38. .. image:: img/grid_snap_button.webp
  39. .. important:: Draw the path in *clockwise* order, or your mobs will spawn
  40. pointing *outwards* instead of *inwards*!
  41. .. image:: img/draw_path2d.gif
  42. After placing point ``4`` in the image, click the "Close Curve" button and your
  43. curve will be complete.
  44. Now that the path is defined, add a :ref:`PathFollow2D <class_PathFollow2D>`
  45. node as a child of ``MobPath`` and name it ``MobSpawnLocation``. This node will
  46. automatically rotate and follow the path as it moves, so we can use it to select
  47. a random position and direction along the path.
  48. Your scene should look like this:
  49. .. image:: img/main_scene_nodes.webp
  50. Main script
  51. ~~~~~~~~~~~
  52. Add a script to ``Main``. At the top of the script, we use
  53. ``@export var mob_scene: PackedScene`` to allow us to choose the Mob scene we want
  54. to instance.
  55. .. tabs::
  56. .. code-tab:: gdscript GDScript
  57. extends Node
  58. @export var mob_scene: PackedScene
  59. var score
  60. .. code-tab:: csharp
  61. using Godot;
  62. public partial class Main : Node
  63. {
  64. // Don't forget to rebuild the project so the editor knows about the new export variable.
  65. [Export]
  66. public PackedScene MobScene { get; set; }
  67. private int _score;
  68. }
  69. Click the ``Main`` node and you will see the ``Mob Scene`` property in the Inspector
  70. under "Main.gd".
  71. You can assign this property's value in two ways:
  72. - Drag ``mob.tscn`` from the "FileSystem" dock and drop it in the **Mob Scene**
  73. property.
  74. - Click the down arrow next to "[empty]" and choose "Load". Select ``mob.tscn``.
  75. Next, select the instance of the ``Player`` scene under ``Main`` node in the Scene dock,
  76. and access the Node dock on the sidebar. Make sure to have the Signals tab selected
  77. in the Node dock.
  78. You should see a list of the signals for the ``Player`` node. Find and
  79. double-click the ``hit`` signal in the list (or right-click it and select
  80. "Connect..."). This will open the signal connection dialog. We want to make a
  81. new function named ``game_over``, which will handle what needs to happen when a
  82. game ends. Type "game_over" in the "Receiver Method" box at the bottom of the
  83. signal connection dialog and click "Connect". You are aiming to have the ``hit`` signal
  84. emitted from ``Player`` and handled in the ``Main`` script. Add the following code
  85. to the new function, as well as a ``new_game`` function that will set
  86. everything up for a new game:
  87. .. tabs::
  88. .. code-tab:: gdscript GDScript
  89. func game_over():
  90. $ScoreTimer.stop()
  91. $MobTimer.stop()
  92. func new_game():
  93. score = 0
  94. $Player.start($StartPosition.position)
  95. $StartTimer.start()
  96. .. code-tab:: csharp
  97. public void GameOver()
  98. {
  99. GetNode<Timer>("MobTimer").Stop();
  100. GetNode<Timer>("ScoreTimer").Stop();
  101. }
  102. public void NewGame()
  103. {
  104. _score = 0;
  105. var player = GetNode<Player>("Player");
  106. var startPosition = GetNode<Marker2D>("StartPosition");
  107. player.Start(startPosition.Position);
  108. GetNode<Timer>("StartTimer").Start();
  109. }
  110. Now connect the ``timeout()`` signal of each of the Timer nodes (``StartTimer``,
  111. ``ScoreTimer``, and ``MobTimer``) to the main script. ``StartTimer`` will start
  112. the other two timers. ``ScoreTimer`` will increment the score by 1.
  113. .. tabs::
  114. .. code-tab:: gdscript GDScript
  115. func _on_score_timer_timeout():
  116. score += 1
  117. func _on_start_timer_timeout():
  118. $MobTimer.start()
  119. $ScoreTimer.start()
  120. .. code-tab:: csharp
  121. // We also specified this function name in PascalCase in the editor's connection window.
  122. private void OnScoreTimerTimeout()
  123. {
  124. _score++;
  125. }
  126. // We also specified this function name in PascalCase in the editor's connection window.
  127. private void OnStartTimerTimeout()
  128. {
  129. GetNode<Timer>("MobTimer").Start();
  130. GetNode<Timer>("ScoreTimer").Start();
  131. }
  132. In ``_on_mob_timer_timeout()``, we will create a mob instance, pick a random
  133. starting location along the ``Path2D``, and set the mob in motion. The
  134. ``PathFollow2D`` node will automatically rotate as it follows the path, so we
  135. will use that to select the mob's direction as well as its position.
  136. When we spawn a mob, we'll pick a random value between ``150.0`` and
  137. ``250.0`` for how fast each mob will move (it would be boring if they were
  138. all moving at the same speed).
  139. Note that a new instance must be added to the scene using ``add_child()``.
  140. .. tabs::
  141. .. code-tab:: gdscript GDScript
  142. func _on_mob_timer_timeout():
  143. # Create a new instance of the Mob scene.
  144. var mob = mob_scene.instantiate()
  145. # Choose a random location on Path2D.
  146. var mob_spawn_location = $MobPath/MobSpawnLocation
  147. mob_spawn_location.progress_ratio = randf()
  148. # Set the mob's direction perpendicular to the path direction.
  149. var direction = mob_spawn_location.rotation + PI / 2
  150. # Set the mob's position to a random location.
  151. mob.position = mob_spawn_location.position
  152. # Add some randomness to the direction.
  153. direction += randf_range(-PI / 4, PI / 4)
  154. mob.rotation = direction
  155. # Choose the velocity for the mob.
  156. var velocity = Vector2(randf_range(150.0, 250.0), 0.0)
  157. mob.linear_velocity = velocity.rotated(direction)
  158. # Spawn the mob by adding it to the Main scene.
  159. add_child(mob)
  160. .. code-tab:: csharp
  161. // We also specified this function name in PascalCase in the editor's connection window.
  162. private void OnMobTimerTimeout()
  163. {
  164. // Create a new instance of the Mob scene.
  165. Mob mob = MobScene.Instantiate<Mob>();
  166. // Choose a random location on Path2D.
  167. var mobSpawnLocation = GetNode<PathFollow2D>("MobPath/MobSpawnLocation");
  168. mobSpawnLocation.ProgressRatio = GD.Randf();
  169. // Set the mob's direction perpendicular to the path direction.
  170. float direction = mobSpawnLocation.Rotation + Mathf.Pi / 2;
  171. // Set the mob's position to a random location.
  172. mob.Position = mobSpawnLocation.Position;
  173. // Add some randomness to the direction.
  174. direction += (float)GD.RandRange(-Mathf.Pi / 4, Mathf.Pi / 4);
  175. mob.Rotation = direction;
  176. // Choose the velocity.
  177. var velocity = new Vector2((float)GD.RandRange(150.0, 250.0), 0);
  178. mob.LinearVelocity = velocity.Rotated(direction);
  179. // Spawn the mob by adding it to the Main scene.
  180. AddChild(mob);
  181. }
  182. .. important:: Why ``PI``? In functions requiring angles, Godot uses *radians*,
  183. not degrees. Pi represents a half turn in radians, about
  184. ``3.1415`` (there is also ``TAU`` which is equal to ``2 * PI``).
  185. If you're more comfortable working with degrees, you'll need to
  186. use the ``deg_to_rad()`` and ``rad_to_deg()`` functions to
  187. convert between the two.
  188. Testing the scene
  189. ~~~~~~~~~~~~~~~~~
  190. Let's test the scene to make sure everything is working. Add this ``new_game``
  191. call to ``_ready()``:
  192. .. tabs::
  193. .. code-tab:: gdscript GDScript
  194. func _ready():
  195. new_game()
  196. .. code-tab:: csharp
  197. public override void _Ready()
  198. {
  199. NewGame();
  200. }
  201. Let's also assign ``Main`` as our "Main Scene" - the one that runs automatically
  202. when the game launches. Press the "Play" button and select ``main.tscn`` when
  203. prompted.
  204. .. tip:: If you had already set another scene as the "Main Scene", you can right
  205. click ``main.tscn`` in the FileSystem dock and select "Set As Main Scene".
  206. You should be able to move the player around, see mobs spawning, and see the
  207. player disappear when hit by a mob.
  208. When you're sure everything is working, remove the call to ``new_game()`` from
  209. ``_ready()`` and replace it with ``pass``.
  210. What's our game lacking? Some user interface. In the next lesson, we'll add a
  211. title screen and display the player's score.