Heads up display

    Create a new scene, and add a CanvasLayer node named . “HUD” stands for “heads-up display”, an informational display that appears as an overlay on top of the game view.

    The node lets us draw our UI elements on a layer above the rest of the game, so that the information it displays isn’t covered up by any game elements like the player or mobs.

    The HUD needs to display the following information:

    • Score, changed by ScoreTimer.

    • A message, such as “Game Over” or “Get Ready!”

    • A “Start” button to begin the game.

    The basic node for UI elements is Control. To create our UI, we’ll use two types of nodes: Label and .

    Create the following as children of the HUD node:

    • Label named ScoreLabel.

    • named Message.

    • Button named StartButton.

    • named MessageTimer.

    Click on the ScoreLabel and type a number into the Text field in the Inspector. The default font for Control nodes is small and doesn’t scale well. There is a font file included in the game assets called “Xolonium-Regular.ttf”. To use this font, do the following:

    1. Under Theme overrides > Fonts click on the empty box and select “New DynamicFont”

    1. Click on the “DynamicFont” you added, and under Font > FontData, choose “Load” and select the “Xolonium-Regular.ttf” file.

    ../../_images/custom_font2.png

    Set the “Size” property under Settings, 64 works well.

    Once you’ve done this on the ScoreLabel, you can click the down arrow next to the Font property and choose “Copy”, then “Paste” it in the same place on the other two Control nodes.

    Note

    Anchors and Margins: Control nodes have a position and size, but they also have anchors and margins. Anchors define the origin - the reference point for the edges of the node. Margins update automatically when you move or resize a control node. They represent the distance from the control node’s edges to its anchor.

    Arrange the nodes as shown below. Click the “Layout” button to set a Control node’s layout:

    You can drag the nodes to place them manually, or for more precise placement, use the following settings:

    • Layout : “Top Wide”

    • Text : 0

    • Align : “Center”

    • Layout : “HCenter Wide”

    • Text : Dodge the Creeps!

    • Align : “Center”

    • Autowrap : “On”

    • Text : Start

    • Layout : “Center Bottom”

    • Margin :

      • Top: -200

      • Bottom: -100

    On the MessageTimer, set the Wait Time to 2 and set the One Shot property to “On”.

    Now add this script to HUD:

    GDScript   C#C++

    1. public class HUD : CanvasLayer
    2. {
    3. // Don't forget to rebuild the project so the editor knows about the new signal.
    4. [Signal]
    5. public delegate void StartGame();
    6. }
    1. // Copy `player.gdns` to `hud.gdns` and replace `Player` with `HUD`.
    2. // Attach the `hud.gdns` file to the HUD node.
    3. // Create two files `hud.cpp` and `hud.hpp` next to `entry.cpp` in `src`.
    4. // This code goes in `hud.hpp`. We also define the methods we'll be using here.
    5. #ifndef HUD_H
    6. #define HUD_H
    7. #include <Button.hpp>
    8. #include <CanvasLayer.hpp>
    9. #include <Godot.hpp>
    10. #include <Label.hpp>
    11. #include <Timer.hpp>
    12. class HUD : public godot::CanvasLayer {
    13. GODOT_CLASS(HUD, godot::CanvasLayer)
    14. godot::Label *_score_label;
    15. godot::Label *_message_label;
    16. godot::Timer *_start_message_timer;
    17. godot::Timer *_get_ready_message_timer;
    18. godot::Button *_start_button;
    19. godot::Timer *_start_button_timer;
    20. public:
    21. void _init() {}
    22. void _ready();
    23. void show_get_ready();
    24. void show_game_over();
    25. void update_score(const int score);
    26. void _on_StartButton_pressed();
    27. void _on_StartMessageTimer_timeout();
    28. void _on_GetReadyMessageTimer_timeout();
    29. static void _register_methods();
    30. };
    31. #endif // HUD_H

    The start_game signal tells the Main node that the button has been pressed.

    GDScript   C#C++

    1. func show_message(text):
    2. $Message.text = text
    3. $Message.show()
    4. $MessageTimer.start()
    1. {
    2. var message = GetNode<Label>("Message");
    3. message.Text = text;
    4. message.Show();
    5. GetNode<Timer>("MessageTimer").Start();
    6. }
    1. // This code goes in `hud.cpp`.
    2. #include "hud.hpp"
    3. void HUD::_ready() {
    4. _score_label = get_node<godot::Label>("ScoreLabel");
    5. _message_label = get_node<godot::Label>("MessageLabel");
    6. _start_message_timer = get_node<godot::Timer>("StartMessageTimer");
    7. _get_ready_message_timer = get_node<godot::Timer>("GetReadyMessageTimer");
    8. _start_button = get_node<godot::Button>("StartButton");
    9. _start_button_timer = get_node<godot::Timer>("StartButtonTimer");
    10. }
    11. void HUD::_register_methods() {
    12. godot::register_method("_ready", &HUD::_ready);
    13. godot::register_method("show_get_ready", &HUD::show_get_ready);
    14. godot::register_method("show_game_over", &HUD::show_game_over);
    15. godot::register_method("update_score", &HUD::update_score);
    16. godot::register_method("_on_StartButton_pressed", &HUD::_on_StartButton_pressed);
    17. godot::register_method("_on_StartMessageTimer_timeout", &HUD::_on_StartMessageTimer_timeout);
    18. godot::register_method("_on_GetReadyMessageTimer_timeout", &HUD::_on_GetReadyMessageTimer_timeout);
    19. godot::register_signal<HUD>("start_game", godot::Dictionary());
    20. }

    This function is called when we want to display a message temporarily, such as “Get Ready”.

    GDScript   C#C++

    1. func show_game_over():
    2. show_message("Game Over")
    3. # Wait until the MessageTimer has counted down.
    4. yield($MessageTimer, "timeout")
    5. $Message.text = "Dodge the\nCreeps!"
    6. $Message.show()
    7. # Make a one-shot timer and wait for it to finish.
    8. yield(get_tree().create_timer(1), "timeout")
    9. $StartButton.show()
    1. async public void ShowGameOver()
    2. {
    3. ShowMessage("Game Over");
    4. var messageTimer = GetNode<Timer>("MessageTimer");
    5. await ToSignal(messageTimer, "timeout");
    6. var message = GetNode<Label>("Message");
    7. message.Text = "Dodge the\nCreeps!";
    8. message.Show();
    9. await ToSignal(GetTree().CreateTimer(1), "timeout");
    10. GetNode<Button>("StartButton").Show();
    11. }
    1. // This code goes in `hud.cpp`.
    2. // There is no `yield` in GDNative, so we need to have every
    3. // step be its own method that is called on timer timeout.
    4. void HUD::show_get_ready() {
    5. _message_label->show();
    6. _get_ready_message_timer->start();
    7. }
    8. void HUD::show_game_over() {
    9. _message_label->set_text("Game Over");
    10. _message_label->show();
    11. _start_message_timer->start();
    12. }

    This function is called when the player loses. It will show “Game Over” for 2 seconds, then return to the title screen and, after a brief pause, show the “Start” button.

    When you need to pause for a brief time, an alternative to using a Timer node is to use the SceneTree’s create_timer() function. This can be very useful to add delays such as in the above code, where we want to wait some time before showing the “Start” button.

    GDScript   C#C++

    1. public void UpdateScore(int score)
    2. {
    3. GetNode<Label>("ScoreLabel").Text = score.ToString();
    4. }
    1. // This code goes in `hud.cpp`.
    2. void HUD::update_score(const int p_score) {
    3. }

    This function is called by Main whenever the score changes.

    Connect the timeout() signal of MessageTimer and the pressed() signal of StartButton and add the following code to the new functions:

    GDScript   C#C++

    1. func _on_StartButton_pressed():
    2. $StartButton.hide()
    3. emit_signal("start_game")
    4. func _on_MessageTimer_timeout():
    5. $Message.hide()
    1. public void OnStartButtonPressed()
    2. {
    3. GetNode<Button>("StartButton").Hide();
    4. EmitSignal("StartGame");
    5. }
    6. public void OnMessageTimerTimeout()
    7. {
    8. GetNode<Label>("Message").Hide();
    9. }
    1. // This code goes in `hud.cpp`.
    2. void HUD::_on_StartButton_pressed() {
    3. _start_button_timer->stop();
    4. _start_button->hide();
    5. emit_signal("start_game");
    6. }
    7. void HUD::_on_StartMessageTimer_timeout() {
    8. _message_label->set_text("Dodge the\nCreeps");
    9. _message_label->show();
    10. _start_button_timer->start();
    11. }
    12. void HUD::_on_GetReadyMessageTimer_timeout() {
    13. _message_label->hide();
    14. }

    Now that we’re done creating the HUD scene, go back to Main. Instance the HUD scene in Main like you did the Player scene. The scene tree should look like this, so make sure you didn’t miss anything:

    ../../_images/completed_main_scene.png

    Now we need to connect the HUD functionality to our Main script. This requires a few additions to the Main scene:

    In the Node tab, connect the HUD’s start_game signal to the new_game() function of the Main node by typing “new_game” in the “Receiver Method” in the “Connect a Signal” window. Verify that the green connection icon now appears next to func new_game() in the script.

    In new_game(), update the score display and show the “Get Ready” message:

    GDScript   C#C++

    1. $HUD.update_score(score)
    2. $HUD.show_message("Get Ready")
    1. var hud = GetNode<HUD>("HUD");
    2. hud.UpdateScore(Score);
    3. hud.ShowMessage("Get Ready!");
    1. _hud->update_score(score);
    2. _hud->show_get_ready();

    In game_over() we need to call the corresponding HUD function:

    GDScript   C#C++

    1. GetNode<HUD>("HUD").ShowGameOver();
    1. _hud->show_game_over();

    Finally, add this to _on_ScoreTimer_timeout() to keep the display in sync with the changing score:

    GDScript   C#C++

    1. $HUD.update_score(score)
    1. GetNode<HUD>("HUD").UpdateScore(Score);
    1. _hud->update_score(score);

    Now you’re ready to play! Click the “Play the Project” button. You will be asked to select a main scene, so choose Main.tscn.

    If you play until “Game Over” and then start a new game right away, the creeps from the previous game may still be on the screen. It would be better if they all disappeared at the start of a new game. We just need a way to tell all the mobs to remove themselves. We can do this with the “group” feature.

    In the Mob scene, select the root node and click the “Node” tab next to the Inspector (the same place where you find the node’s signals). Next to “Signals”, click “Groups” and you can type a new group name and click “Add”.

    Now all mobs will be in the “mobs” group. We can then add the following line to the new_game() function in Main:

    GDScript   C#C++

    1. get_tree().call_group("mobs", "queue_free")
    1. // Note that for calling Godot-provided methods with strings,
    2. // we have to use the original Godot snake_case name.
    3. GetTree().CallGroup("mobs", "queue_free");
    1. get_tree()->call_group("mobs", "queue_free");

    The game’s mostly done at this point. In the next and last part, we’ll polish it a bit by adding a background, looping music, and some keyboard shortcuts.