05.the_main_game_scene.rst 9.7 KB

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