05.the_main_game_scene.rst 15 KB

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