05.the_main_game_scene.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. .. code-tab:: cpp
  71. // Copy `player.gdns` to `main.gdns` and replace `Player` with `Main`.
  72. // Attach the `main.gdns` file to the Main node.
  73. // Create two files `main.cpp` and `main.hpp` next to `entry.cpp` in `src`.
  74. // This code goes in `main.hpp`. We also define the methods we'll be using here.
  75. #ifndef MAIN_H
  76. #define MAIN_H
  77. #include <AudioStreamPlayer.hpp>
  78. #include <CanvasLayer.hpp>
  79. #include <Godot.hpp>
  80. #include <Node.hpp>
  81. #include <PackedScene.hpp>
  82. #include <PathFollow2D.hpp>
  83. #include <RandomNumberGenerator.hpp>
  84. #include <Timer.hpp>
  85. #include "hud.hpp"
  86. #include "player.hpp"
  87. class Main : public godot::Node {
  88. GODOT_CLASS(Main, godot::Node)
  89. int score;
  90. HUD *_hud;
  91. Player *_player;
  92. godot::Node2D *_start_position;
  93. godot::PathFollow2D *_mob_spawn_location;
  94. godot::Timer *_mob_timer;
  95. godot::Timer *_score_timer;
  96. godot::Timer *_start_timer;
  97. godot::AudioStreamPlayer *_music;
  98. godot::AudioStreamPlayer *_death_sound;
  99. godot::Ref<godot::RandomNumberGenerator> _random;
  100. public:
  101. godot::Ref<godot::PackedScene> mob_scene;
  102. void _init() {}
  103. void _ready();
  104. void game_over();
  105. void new_game();
  106. void _on_MobTimer_timeout();
  107. void _on_ScoreTimer_timeout();
  108. void _on_StartTimer_timeout();
  109. static void _register_methods();
  110. };
  111. #endif // MAIN_H
  112. // This code goes in `main.cpp`.
  113. #include "main.hpp"
  114. #include <SceneTree.hpp>
  115. #include "mob.hpp"
  116. void Main::_ready() {
  117. _hud = get_node<HUD>("HUD");
  118. _player = get_node<Player>("Player");
  119. _start_position = get_node<godot::Node2D>("StartPosition");
  120. _mob_spawn_location = get_node<godot::PathFollow2D>("MobPath/MobSpawnLocation");
  121. _mob_timer = get_node<godot::Timer>("MobTimer");
  122. _score_timer = get_node<godot::Timer>("ScoreTimer");
  123. _start_timer = get_node<godot::Timer>("StartTimer");
  124. // Uncomment these after adding the nodes in the "Sound effects" section of "Finishing up".
  125. //_music = get_node<godot::AudioStreamPlayer>("Music");
  126. //_death_sound = get_node<godot::AudioStreamPlayer>("DeathSound");
  127. _random = (godot::Ref<godot::RandomNumberGenerator>)godot::RandomNumberGenerator::_new();
  128. }
  129. Click the ``Main`` node and you will see the ``Mob Scene`` property in the Inspector
  130. under "Script Variables".
  131. You can assign this property's value in two ways:
  132. - Drag ``mob.tscn`` from the "FileSystem" dock and drop it in the **Mob Scene**
  133. property.
  134. - Click the down arrow next to "[empty]" and choose "Load". Select ``mob.tscn``.
  135. Next, select the instance of the ``Player`` scene under ``Main`` node in the Scene dock,
  136. and access the Node dock on the sidebar. Make sure to have the Signals tab selected
  137. in the Node dock.
  138. You should see a list of the signals for the ``Player`` node. Find and
  139. double-click the ``hit`` signal in the list (or right-click it and select
  140. "Connect..."). This will open the signal connection dialog. We want to make a
  141. new function named ``game_over``, which will handle what needs to happen when a
  142. game ends. Type "game_over" in the "Receiver Method" box at the bottom of the
  143. signal connection dialog and click "Connect". You are aiming to have the ``hit`` signal
  144. emitted from ``Player`` and handled in the ``Main`` script. Add the following code
  145. to the new function, as well as a ``new_game`` function that will set
  146. everything up for a new game:
  147. .. tabs::
  148. .. code-tab:: gdscript GDScript
  149. func game_over():
  150. $ScoreTimer.stop()
  151. $MobTimer.stop()
  152. func new_game():
  153. score = 0
  154. $Player.start($StartPosition.position)
  155. $StartTimer.start()
  156. .. code-tab:: csharp
  157. public void GameOver()
  158. {
  159. GetNode<Timer>("MobTimer").Stop();
  160. GetNode<Timer>("ScoreTimer").Stop();
  161. }
  162. public void NewGame()
  163. {
  164. _score = 0;
  165. var player = GetNode<Player>("Player");
  166. var startPosition = GetNode<Marker2D>("StartPosition");
  167. player.Start(startPosition.Position);
  168. GetNode<Timer>("StartTimer").Start();
  169. }
  170. .. code-tab:: cpp
  171. // This code goes in `main.cpp`.
  172. void Main::game_over() {
  173. _score_timer->stop();
  174. _mob_timer->stop();
  175. }
  176. void Main::new_game() {
  177. score = 0;
  178. _player->start(_start_position->get_position());
  179. _start_timer->start();
  180. }
  181. Now connect the ``timeout()`` signal of each of the Timer nodes (``StartTimer``,
  182. ``ScoreTimer``, and ``MobTimer``) to the main script. ``StartTimer`` will start
  183. the other two timers. ``ScoreTimer`` will increment the score by 1.
  184. .. tabs::
  185. .. code-tab:: gdscript GDScript
  186. func _on_score_timer_timeout():
  187. score += 1
  188. func _on_start_timer_timeout():
  189. $MobTimer.start()
  190. $ScoreTimer.start()
  191. .. code-tab:: csharp
  192. private void OnScoreTimerTimeout()
  193. {
  194. _score++;
  195. }
  196. private void OnStartTimerTimeout()
  197. {
  198. GetNode<Timer>("MobTimer").Start();
  199. GetNode<Timer>("ScoreTimer").Start();
  200. }
  201. .. code-tab:: cpp
  202. // This code goes in `main.cpp`.
  203. void Main::_on_ScoreTimer_timeout() {
  204. score += 1;
  205. }
  206. void Main::_on_StartTimer_timeout() {
  207. _mob_timer->start();
  208. _score_timer->start();
  209. }
  210. // Also add this to register all methods and the mob scene property.
  211. void Main::_register_methods() {
  212. godot::register_method("_ready", &Main::_ready);
  213. godot::register_method("game_over", &Main::game_over);
  214. godot::register_method("new_game", &Main::new_game);
  215. godot::register_method("_on_MobTimer_timeout", &Main::_on_MobTimer_timeout);
  216. godot::register_method("_on_ScoreTimer_timeout", &Main::_on_ScoreTimer_timeout);
  217. godot::register_method("_on_StartTimer_timeout", &Main::_on_StartTimer_timeout);
  218. godot::register_property("mob_scene", &Main::mob_scene, (godot::Ref<godot::PackedScene>)nullptr);
  219. }
  220. In ``_on_mob_timer_timeout()``, we will create a mob instance, pick a random
  221. starting location along the ``Path2D``, and set the mob in motion. The
  222. ``PathFollow2D`` node will automatically rotate as it follows the path, so we
  223. will use that to select the mob's direction as well as its position.
  224. When we spawn a mob, we'll pick a random value between ``150.0`` and
  225. ``250.0`` for how fast each mob will move (it would be boring if they were
  226. all moving at the same speed).
  227. Note that a new instance must be added to the scene using ``add_child()``.
  228. .. tabs::
  229. .. code-tab:: gdscript GDScript
  230. func _on_mob_timer_timeout():
  231. # Create a new instance of the Mob scene.
  232. var mob = mob_scene.instantiate()
  233. # Choose a random location on Path2D.
  234. var mob_spawn_location = get_node("MobPath/MobSpawnLocation")
  235. mob_spawn_location.progress_ratio = randf()
  236. # Set the mob's direction perpendicular to the path direction.
  237. var direction = mob_spawn_location.rotation + PI / 2
  238. # Set the mob's position to a random location.
  239. mob.position = mob_spawn_location.position
  240. # Add some randomness to the direction.
  241. direction += randf_range(-PI / 4, PI / 4)
  242. mob.rotation = direction
  243. # Choose the velocity for the mob.
  244. var velocity = Vector2(randf_range(150.0, 250.0), 0.0)
  245. mob.linear_velocity = velocity.rotated(direction)
  246. # Spawn the mob by adding it to the Main scene.
  247. add_child(mob)
  248. .. code-tab:: csharp
  249. private void OnMobTimerTimeout()
  250. {
  251. // Note: Normally it is best to use explicit types rather than the `var`
  252. // keyword. However, var is acceptable to use here because the types are
  253. // obviously Mob and PathFollow2D, since they appear later on the line.
  254. // Create a new instance of the Mob scene.
  255. Mob mob = MobScene.Instantiate<Mob>();
  256. // Choose a random location on Path2D.
  257. var mobSpawnLocation = GetNode<PathFollow2D>("MobPath/MobSpawnLocation");
  258. mobSpawnLocation.ProgressRatio = GD.Randf();
  259. // Set the mob's direction perpendicular to the path direction.
  260. float direction = mobSpawnLocation.Rotation + Mathf.Pi / 2;
  261. // Set the mob's position to a random location.
  262. mob.Position = mobSpawnLocation.Position;
  263. // Add some randomness to the direction.
  264. direction += (float)GD.RandRange(-Mathf.Pi / 4, Mathf.Pi / 4);
  265. mob.Rotation = direction;
  266. // Choose the velocity.
  267. var velocity = new Vector2((float)GD.RandRange(150.0, 250.0), 0);
  268. mob.LinearVelocity = velocity.Rotated(direction);
  269. // Spawn the mob by adding it to the Main scene.
  270. AddChild(mob);
  271. }
  272. .. code-tab:: cpp
  273. // This code goes in `main.cpp`.
  274. void Main::_on_MobTimer_timeout() {
  275. // Create a new instance of the Mob scene.
  276. godot::Node *mob = mob_scene->instance();
  277. // Choose a random location on Path2D.
  278. _mob_spawn_location->set_progress_ratio((real_t)_random->randf());
  279. // Set the mob's direction perpendicular to the path direction.
  280. real_t direction = _mob_spawn_location->get_rotation() + (real_t)Math_PI / 2;
  281. // Set the mob's position to a random location.
  282. mob->set("position", _mob_spawn_location->get_position());
  283. // Add some randomness to the direction.
  284. direction += _random->randf_range((real_t)-Math_PI / 4, (real_t)Math_PI / 4);
  285. mob->set("rotation", direction);
  286. // Choose the velocity for the mob.
  287. godot::Vector2 velocity = godot::Vector2(_random->randf_range(150.0, 250.0), 0.0);
  288. mob->set("linear_velocity", velocity.rotated(direction));
  289. // Spawn the mob by adding it to the Main scene.
  290. add_child(mob);
  291. }
  292. .. important:: Why ``PI``? In functions requiring angles, Godot uses *radians*,
  293. not degrees. Pi represents a half turn in radians, about
  294. ``3.1415`` (there is also ``TAU`` which is equal to ``2 * PI``).
  295. If you're more comfortable working with degrees, you'll need to
  296. use the ``deg_to_rad()`` and ``rad_to_deg()`` functions to
  297. convert between the two.
  298. Testing the scene
  299. ~~~~~~~~~~~~~~~~~
  300. Let's test the scene to make sure everything is working. Add this ``new_game``
  301. call to ``_ready()``:
  302. .. tabs::
  303. .. code-tab:: gdscript GDScript
  304. func _ready():
  305. new_game()
  306. .. code-tab:: csharp
  307. public override void _Ready()
  308. {
  309. NewGame();
  310. }
  311. .. code-tab:: cpp
  312. // This code goes in `main.cpp`.
  313. void Main::_ready() {
  314. new_game();
  315. }
  316. Let's also assign ``Main`` as our "Main Scene" - the one that runs automatically
  317. when the game launches. Press the "Play" button and select ``main.tscn`` when
  318. prompted.
  319. .. tip:: If you had already set another scene as the "Main Scene", you can right
  320. click ``main.tscn`` in the FileSystem dock and select "Set As Main Scene".
  321. You should be able to move the player around, see mobs spawning, and see the
  322. player disappear when hit by a mob.
  323. When you're sure everything is working, remove the call to ``new_game()`` from
  324. ``_ready()``.
  325. What's our game lacking? Some user interface. In the next lesson, we'll add a
  326. title screen and display the player's score.