Heads up display

The final piece our game needs is a User Interface (UI) to display things like score, a “game over” message, and a restart button.

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

The CanvasLayer 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 Control nodes: Label and Button.

Create the following as children of the HUD node:

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:

Under “Theme Overrides > Fonts”, choose “Load” and select the “Xolonium-Regular.ttf” file.

../../_images/custom_font_load_font.webp

The font size is still too small, increase it to 64 under “Theme Overrides > Font Sizes”. Once you’ve done this with the ScoreLabel, repeat the changes for the Message and StartButton nodes.

../../_images/custom_font_size.webp

Note

Anchors: Control nodes have a position and size, but they also have anchors. Anchors define the origin - the reference point for the edges of the node.

Arrange the nodes as shown below. You can drag the nodes to place them manually, or for more precise placement, use “Anchor Presets”.

../../_images/ui_anchor.webp

ScoreLabel

  1. Add the text 0.

  2. Set the “Horizontal Alignment” and “Vertical Alignment” to Center.

  3. Choose the “Anchor Preset” Center Top.

Message

  1. Add the text Dodge the Creeps!.

  2. Set the “Horizontal Alignment” and “Vertical Alignment” to Center.

  3. Set the “Autowrap Mode” to Word, otherwise the label will stay on one line.

  4. Under “Control - Layout/Transform” set “Size X” to 480 to use the entire width of the screen.

  5. Choose the “Anchor Preset” Center.

StartButton

  1. Add the text Start.

  2. Under “Control - Layout/Transform”, set “Size X” to 200 and “Size Y” to 100 to add a little bit more padding between the border and text.

  3. Choose the “Anchor Preset” Center Bottom.

  4. Under “Control - Layout/Transform”, set “Position Y” to 580.

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

Now add this script to HUD:

GDScriptC#

  1. extends CanvasLayer
  2. # Notifies `Main` node that the button has been pressed
  3. signal start_game
  1. using Godot;
  2. public partial class HUD : CanvasLayer
  3. {
  4. // Don't forget to rebuild the project so the editor knows about the new signal.
  5. [Signal]
  6. public delegate void StartGameEventHandler();
  7. }

We now want to display a message temporarily, such as “Get Ready”, so we add the following code

GDScriptC#

  1. func show_message(text):
  2. $Message.text = text
  3. $Message.show()
  4. $MessageTimer.start()
  1. public void ShowMessage(string text)
  2. {
  3. var message = GetNode<Label>("Message");
  4. message.Text = text;
  5. message.Show();
  6. GetNode<Timer>("MessageTimer").Start();
  7. }

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.

GDScriptC#

  1. func show_game_over():
  2. show_message("Game Over")
  3. # Wait until the MessageTimer has counted down.
  4. await $MessageTimer.timeout
  5. $Message.text = "Dodge the Creeps!"
  6. $Message.show()
  7. # Make a one-shot timer and wait for it to finish.
  8. await get_tree().create_timer(1.0).timeout
  9. $StartButton.show()
  1. async public void ShowGameOver()
  2. {
  3. ShowMessage("Game Over");
  4. var messageTimer = GetNode<Timer>("MessageTimer");
  5. await ToSignal(messageTimer, Timer.SignalName.Timeout);
  6. var message = GetNode<Label>("Message");
  7. message.Text = "Dodge the Creeps!";
  8. message.Show();
  9. await ToSignal(GetTree().CreateTimer(1.0), SceneTreeTimer.SignalName.Timeout);
  10. GetNode<Button>("StartButton").Show();
  11. }

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.

Note

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.

Add the code below to HUD to update the score

GDScriptC#

  1. func update_score(score):
  2. $ScoreLabel.text = str(score)
  1. public void UpdateScore(int score)
  2. {
  3. GetNode<Label>("ScoreLabel").Text = score.ToString();
  4. }

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

GDScriptC#

  1. func _on_start_button_pressed():
  2. $StartButton.hide()
  3. start_game.emit()
  4. func _on_message_timer_timeout():
  5. $Message.hide()
  1. // We also specified this function name in PascalCase in the editor's connection window.
  2. private void OnStartButtonPressed()
  3. {
  4. GetNode<Button>("StartButton").Hide();
  5. EmitSignal(SignalName.StartGame);
  6. }
  7. // We also specified this function name in PascalCase in the editor's connection window.
  8. private void OnMessageTimerTimeout()
  9. {
  10. GetNode<Label>("Message").Hide();
  11. }

Connecting HUD to Main

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.webp

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 clicking the “Pick” button in the “Connect a Signal” window and selecting the new_game() method or type “new_game” below “Receiver Method” in the 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:

GDScriptC#

  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!");

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

GDScriptC#

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

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

GDScriptC#

  1. $HUD.update_score(score)
  1. GetNode<HUD>("HUD").UpdateScore(_score);

Warning

Remember to remove the call to new_game() from _ready() if you haven’t already, otherwise your game will start automatically.

Now you’re ready to play! Click the “Play the Project” button.

Removing old creeps

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” to open the group overview and the “+” button to open the “Create New Group” dialog.

../../_images/group_tab.webp

Name the group mobs and click “ok” to add a new scene group.

../../_images/add_group_dialog.webp

Now all mobs will be in the “mobs” group.

../../_images/scene_group_mobs.webp

We can then add the following line to the new_game() function in Main:

GDScriptC#

  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", Node.MethodName.QueueFree);

The call_group() function calls the named function on every node in a group - in this case we are telling every mob to delete itself.

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.


User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next