HUD and pause menu
You want a score that follows the game and a pause screen with buttons, without computing text positions in code.
The HUD
Section titled “The HUD”- In Resources, + › Nova interface… and name it
Hud. - Add a Texto named
Moedasat the top corner and a Barra namedVida. - Open the room and, in the Inspector, check
Hudunder Interfaces: it now opens with the room.
In the code of an object in the level, write what each one shows:
#include "Fase.hpp"#include "Moeda.hpp"#include <format>using namespace brasa;
void Fase::onUpdate() { Ui::Element hud = Ui::get("Hud"); hud["Moedas"].setText(std::format("Moedas: {}", moedas)); hud["Vida"].setValue(vida / 100.0f);}The pause screen
Section titled “The pause screen”- Create the
Pausainterface: a Painel in the center with a Texto and three Botões (Continuar,Recomecar,Sair). - To darken the game behind it, add at the end of the list a panel the size of the screen, black with transparency.
- In Project settings, create the
pausaraction (for example, with the Esc key).
The code wires the buttons and the key:
void Fase::onSpawn() { Ui::Element pausa = Ui::get("Pausa"); pausa.hide(); pausa["Continuar"].onClick(this, [] { setPaused(false); Ui::hide("Pausa"); }); pausa["Recomecar"].onClick(this, [this] { restart(); }); pausa["Sair"].onClick(this, [] { quit(); });}
void Fase::onUpdate() { if (pressed("pausar")) { setPaused(true); Ui::show("Pausa"); }}
void Fase::onPausedUpdate() { if (pressed("pausar")) { setPaused(false); Ui::hide("Pausa"); }}How it works
Section titled “How it works”Ui::get("Hud")returns the interface; the brackets return one of its elements by the name set in the editor.setPaused(true)stops the instances: timers,onUpdate, movement and collisions. Drawing and the interface keep going.- While paused, each instance gets
onPausedUpdateinstead ofonUpdate. That is where you read the key that unpauses. - The
thisinonClicksays who owns the code: if the instance is destroyed, the button stops calling it. - Buttons respond to the mouse and the keyboard: the
cima,baixo,esquerdaanddireitaactions move between them, andconfirmarpresses. - The dark panel captures the click: with the pause open, clicks don’t reach the game.
- Each interface exists only once. What the code changes in it still holds after hiding and showing;
Ui::reset("Hud")goes back to what is in the editor.
The Plataforma template already comes with a Hud, a Pausa and a Fim screen built this way. The Zumbis template goes further: a shooter in 1920 × 1080 with a HUD, a shop, pause and game over.
See also
Section titled “See also”- Interface, the editor tab.
- Interface, the code reference.
- Shop with a list of items.
