06.heads_up_display.rst 13 KB

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