2
0

06.heads_up_display.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. .. _doc_your_first_2d_game_heads_up_display:
  2. Heads up display
  3. ================
  4. The final piece our game needs is a User Interface (UI) to display things like
  5. score, a "game over" message, and a restart button.
  6. Create a new scene, and add a :ref:`CanvasLayer <class_CanvasLayer>` node named
  7. ``HUD``. "HUD" stands for "heads-up display", an informational display that
  8. appears as an overlay on top of the game view.
  9. The :ref:`CanvasLayer <class_CanvasLayer>` node lets us draw our UI elements on
  10. a layer above the rest of the game, so that the information it displays isn't
  11. covered up by any game elements like the player or mobs.
  12. The HUD needs to display the following information:
  13. - Score, changed by ``ScoreTimer``.
  14. - A message, such as "Game Over" or "Get Ready!"
  15. - A "Start" button to begin the game.
  16. The basic node for UI elements is :ref:`Control <class_Control>`. To create our
  17. UI, we'll use two types of :ref:`Control <class_Control>` nodes: :ref:`Label
  18. <class_Label>` and :ref:`Button <class_Button>`.
  19. Create the following as children of the ``HUD`` node:
  20. - :ref:`Label <class_Label>` named ``ScoreLabel``.
  21. - :ref:`Label <class_Label>` named ``Message``.
  22. - :ref:`Button <class_Button>` named ``StartButton``.
  23. - :ref:`Timer <class_Timer>` named ``MessageTimer``.
  24. Click on the ``ScoreLabel`` and type a number into the ``Text`` field in the
  25. Inspector. The default font for ``Control`` nodes is small and doesn't scale
  26. well. There is a font file included in the game assets called
  27. "Xolonium-Regular.ttf". To use this font, do the following:
  28. 1. Under "Theme Overrides > Fonts", choose "Load" and select the "Xolonium-Regular.ttf" file.
  29. .. image:: img/custom_font_load_font.webp
  30. Once you've done this on the ``ScoreLabel``, you can click the down arrow next
  31. to the Font property and choose "Copy", then "Paste" it in the same place
  32. on the other two Control nodes.
  33. Set the "Font Size" property of the ``ScoreLabel`` under "Theme Overrides > Font Sizes".
  34. A setting of ``64`` works well.
  35. .. image:: img/custom_font_size.webp
  36. .. note:: **Anchors:** ``Control`` nodes have a position and size,
  37. but they also have anchors. Anchors define the origin -
  38. the reference point for the edges of the node.
  39. Arrange the nodes as shown below.
  40. You can drag the nodes to place them manually, or for more precise placement,
  41. use "Anchor Presets" with the following settings:
  42. .. image:: img/ui_anchor.webp
  43. ScoreLabel
  44. ~~~~~~~~~~
  45. Layout :
  46. - Anchor Preset : ``Center Top``
  47. Label settings :
  48. - Text : ``0``
  49. - Horizontal Alignment : ``Center``
  50. - Vertical Alignment : ``Center``
  51. Message
  52. ~~~~~~~~~~~~
  53. Layout :
  54. - Anchor Preset : ``Center``
  55. Label settings :
  56. - Text : ``Dodge the Creeps!``
  57. - Horizontal Alignment : ``Center``
  58. - Vertical Alignment : ``Center``
  59. - Autowrap Mode : ``Word``
  60. StartButton
  61. ~~~~~~~~~~~
  62. Layout :
  63. - Anchor Preset : ``Center Bottom``
  64. Button settings :
  65. - Text : ``Start``
  66. - Position Y : ``580`` (Control - Layout/Transform)
  67. On the ``MessageTimer``, set the ``Wait Time`` to ``2`` and set the ``One Shot``
  68. property to "On".
  69. Now add this script to ``HUD``:
  70. .. tabs::
  71. .. code-tab:: gdscript GDScript
  72. extends CanvasLayer
  73. # Notifies `Main` node that the button has been pressed
  74. signal start_game
  75. .. code-tab:: csharp
  76. using Godot;
  77. public partial class HUD : CanvasLayer
  78. {
  79. // Don't forget to rebuild the project so the editor knows about the new signal.
  80. [Signal]
  81. public delegate void StartGameEventHandler();
  82. }
  83. .. code-tab:: cpp
  84. // Copy `player.gdns` to `hud.gdns` and replace `Player` with `HUD`.
  85. // Attach the `hud.gdns` file to the HUD node.
  86. // Create two files `hud.cpp` and `hud.hpp` next to `entry.cpp` in `src`.
  87. // This code goes in `hud.hpp`. We also define the methods we'll be using here.
  88. #ifndef HUD_H
  89. #define HUD_H
  90. #include <Button.hpp>
  91. #include <CanvasLayer.hpp>
  92. #include <Godot.hpp>
  93. #include <Label.hpp>
  94. #include <Timer.hpp>
  95. class HUD : public godot::CanvasLayer {
  96. GODOT_CLASS(HUD, godot::CanvasLayer)
  97. godot::Label *_score_label;
  98. godot::Label *_message_label;
  99. godot::Timer *_start_message_timer;
  100. godot::Timer *_get_ready_message_timer;
  101. godot::Button *_start_button;
  102. godot::Timer *_start_button_timer;
  103. public:
  104. void _init() {}
  105. void _ready();
  106. void show_get_ready();
  107. void show_game_over();
  108. void update_score(const int score);
  109. void _on_StartButton_pressed();
  110. void _on_StartMessageTimer_timeout();
  111. void _on_GetReadyMessageTimer_timeout();
  112. static void _register_methods();
  113. };
  114. #endif // HUD_H
  115. We now want to display a message temporarily,
  116. such as "Get Ready", so we add the following code
  117. .. tabs::
  118. .. code-tab:: gdscript GDScript
  119. func show_message(text):
  120. $Message.text = text
  121. $Message.show()
  122. $MessageTimer.start()
  123. .. code-tab:: csharp
  124. public void ShowMessage(string text)
  125. {
  126. var message = GetNode<Label>("Message");
  127. message.Text = text;
  128. message.Show();
  129. GetNode<Timer>("MessageTimer").Start();
  130. }
  131. .. code-tab:: cpp
  132. // This code goes in `hud.cpp`.
  133. #include "hud.hpp"
  134. void HUD::_ready() {
  135. _score_label = get_node<godot::Label>("ScoreLabel");
  136. _message_label = get_node<godot::Label>("MessageLabel");
  137. _start_message_timer = get_node<godot::Timer>("StartMessageTimer");
  138. _get_ready_message_timer = get_node<godot::Timer>("GetReadyMessageTimer");
  139. _start_button = get_node<godot::Button>("StartButton");
  140. _start_button_timer = get_node<godot::Timer>("StartButtonTimer");
  141. }
  142. void HUD::_register_methods() {
  143. godot::register_method("_ready", &HUD::_ready);
  144. godot::register_method("show_get_ready", &HUD::show_get_ready);
  145. godot::register_method("show_game_over", &HUD::show_game_over);
  146. godot::register_method("update_score", &HUD::update_score);
  147. godot::register_method("_on_StartButton_pressed", &HUD::_on_StartButton_pressed);
  148. godot::register_method("_on_StartMessageTimer_timeout", &HUD::_on_StartMessageTimer_timeout);
  149. godot::register_method("_on_GetReadyMessageTimer_timeout", &HUD::_on_GetReadyMessageTimer_timeout);
  150. godot::register_signal<HUD>("start_game", godot::Dictionary());
  151. }
  152. We also need to process what happens when the player loses. The code below will show "Game Over" for 2 seconds, then return to the title screen and, after a brief pause, show the "Start" button.
  153. .. tabs::
  154. .. code-tab:: gdscript GDScript
  155. func show_game_over():
  156. show_message("Game Over")
  157. # Wait until the MessageTimer has counted down.
  158. await $MessageTimer.timeout
  159. $Message.text = "Dodge the\nCreeps!"
  160. $Message.show()
  161. # Make a one-shot timer and wait for it to finish.
  162. await get_tree().create_timer(1.0).timeout
  163. $StartButton.show()
  164. .. code-tab:: csharp
  165. async public void ShowGameOver()
  166. {
  167. ShowMessage("Game Over");
  168. var messageTimer = GetNode<Timer>("MessageTimer");
  169. await ToSignal(messageTimer, Timer.SignalName.Timeout);
  170. var message = GetNode<Label>("Message");
  171. message.Text = "Dodge the\nCreeps!";
  172. message.Show();
  173. await ToSignal(GetTree().CreateTimer(1.0), SceneTreeTimer.SignalName.Timeout);
  174. GetNode<Button>("StartButton").Show();
  175. }
  176. .. code-tab:: cpp
  177. // This code goes in `hud.cpp`.
  178. // There is no `yield` in GDExtension, so we need to have every
  179. // step be its own method that is called on timer timeout.
  180. void HUD::show_get_ready() {
  181. _message_label->set_text("Get Ready");
  182. _message_label->show();
  183. _get_ready_message_timer->start();
  184. }
  185. void HUD::show_game_over() {
  186. _message_label->set_text("Game Over");
  187. _message_label->show();
  188. _start_message_timer->start();
  189. }
  190. This function is called when the player loses. It will show "Game Over" for 2
  191. seconds, then return to the title screen and, after a brief pause, show the
  192. "Start" button.
  193. .. note:: When you need to pause for a brief time, an alternative to using a
  194. Timer node is to use the SceneTree's ``create_timer()`` function. This
  195. can be very useful to add delays such as in the above code, where we
  196. want to wait some time before showing the "Start" button.
  197. Add the code below to ``HUD`` to update the score
  198. .. tabs::
  199. .. code-tab:: gdscript GDScript
  200. func update_score(score):
  201. $ScoreLabel.text = str(score)
  202. .. code-tab:: csharp
  203. public void UpdateScore(int score)
  204. {
  205. GetNode<Label>("ScoreLabel").Text = score.ToString();
  206. }
  207. .. code-tab:: cpp
  208. // This code goes in `hud.cpp`.
  209. void HUD::update_score(const int p_score) {
  210. _score_label->set_text(godot::Variant(p_score));
  211. }
  212. Connect the ``timeout()`` signal of ``MessageTimer`` and the ``pressed()``
  213. signal of ``StartButton``, and add the following code to the new functions:
  214. .. tabs::
  215. .. code-tab:: gdscript GDScript
  216. func _on_start_button_pressed():
  217. $StartButton.hide()
  218. start_game.emit()
  219. func _on_message_timer_timeout():
  220. $Message.hide()
  221. .. code-tab:: csharp
  222. private void OnStartButtonPressed()
  223. {
  224. GetNode<Button>("StartButton").Hide();
  225. EmitSignal(SignalName.StartGame);
  226. }
  227. private void OnMessageTimerTimeout()
  228. {
  229. GetNode<Label>("Message").Hide();
  230. }
  231. .. code-tab:: cpp
  232. // This code goes in `hud.cpp`.
  233. void HUD::_on_StartButton_pressed() {
  234. _start_button_timer->stop();
  235. _start_button->hide();
  236. emit_signal("start_game");
  237. }
  238. void HUD::_on_StartMessageTimer_timeout() {
  239. _message_label->set_text("Dodge the\nCreeps");
  240. _message_label->show();
  241. _start_button_timer->start();
  242. }
  243. void HUD::_on_GetReadyMessageTimer_timeout() {
  244. _message_label->hide();
  245. }
  246. Connecting HUD to Main
  247. ~~~~~~~~~~~~~~~~~~~~~~
  248. Now that we're done creating the ``HUD`` scene, go back to ``Main``. Instance
  249. the ``HUD`` scene in ``Main`` like you did the ``Player`` scene. The scene tree
  250. should look like this, so make sure you didn't miss anything:
  251. .. image:: img/completed_main_scene.webp
  252. Now we need to connect the ``HUD`` functionality to our ``Main`` script. This
  253. requires a few additions to the ``Main`` scene:
  254. In the Node tab, connect the HUD's ``start_game`` signal to the ``new_game()``
  255. function of the Main node by clicking the "Pick" button in the "Connect a Signal"
  256. window and selecting the ``new_game()`` method or type "new_game" below "Receiver Method"
  257. in the window. Verify that the green connection icon now appears next to
  258. ``func new_game()`` in the script.
  259. Remember to remove the call to ``new_game()`` from
  260. ``_ready()``.
  261. In ``new_game()``, update the score display and show the "Get Ready" message:
  262. .. tabs::
  263. .. code-tab:: gdscript GDScript
  264. $HUD.update_score(score)
  265. $HUD.show_message("Get Ready")
  266. .. code-tab:: csharp
  267. var hud = GetNode<HUD>("HUD");
  268. hud.UpdateScore(_score);
  269. hud.ShowMessage("Get Ready!");
  270. .. code-tab:: cpp
  271. _hud->update_score(score);
  272. _hud->show_get_ready();
  273. In ``game_over()`` we need to call the corresponding ``HUD`` function:
  274. .. tabs::
  275. .. code-tab:: gdscript GDScript
  276. $HUD.show_game_over()
  277. .. code-tab:: csharp
  278. GetNode<HUD>("HUD").ShowGameOver();
  279. .. code-tab:: cpp
  280. _hud->show_game_over();
  281. Just a reminder: we don't want to start the new game automatically, so
  282. remove the call to ``new_game()`` in ``_ready()`` if you haven't yet.
  283. Finally, add this to ``_on_score_timer_timeout()`` to keep the display in sync
  284. with the changing score:
  285. .. tabs::
  286. .. code-tab:: gdscript GDScript
  287. $HUD.update_score(score)
  288. .. code-tab:: csharp
  289. GetNode<HUD>("HUD").UpdateScore(_score);
  290. .. code-tab:: cpp
  291. _hud->update_score(score);
  292. Now you're ready to play! Click the "Play the Project" button. You will be asked
  293. to select a main scene, so choose ``main.tscn``.
  294. Removing old creeps
  295. ~~~~~~~~~~~~~~~~~~~
  296. If you play until "Game Over" and then start a new game right away, the creeps
  297. from the previous game may still be on the screen. It would be better if they
  298. all disappeared at the start of a new game. We just need a way to tell *all* the
  299. mobs to remove themselves. We can do this with the "group" feature.
  300. In the ``Mob`` scene, select the root node and click the "Node" tab next to the
  301. Inspector (the same place where you find the node's signals). Next to "Signals",
  302. click "Groups" and you can type a new group name and click "Add".
  303. .. image:: img/group_tab.webp
  304. Now all mobs will be in the "mobs" group. We can then add the following line to
  305. the ``new_game()`` function in ``Main``:
  306. .. tabs::
  307. .. code-tab:: gdscript GDScript
  308. get_tree().call_group("mobs", "queue_free")
  309. .. code-tab:: csharp
  310. // Note that for calling Godot-provided methods with strings,
  311. // we have to use the original Godot snake_case name.
  312. GetTree().CallGroup("mobs", Node.MethodName.QueueFree);
  313. .. code-tab:: cpp
  314. get_tree()->call_group("mobs", "queue_free");
  315. The ``call_group()`` function calls the named function on every node in a
  316. group - in this case we are telling every mob to delete itself.
  317. The game's mostly done at this point. In the next and last part, we'll polish it
  318. a bit by adding a background, looping music, and some keyboard shortcuts.