Hazel

Game UI

Game UI is everything your players see on top of the game: health bars, score counters, menus, buttons and pop-ups. In Renzora you write it as small .html UI templates, put each one on a UI Canvas, and bring it to life from a script.

If you have ever written a web page this will feel familiar. If you haven't, the examples are short enough to copy and change.

The UI workspace with a main menu template open: the hierarchy and UI Widgets on the left, the UI Editor in the middle, the Inspector on the right

Your first UI

  1. Right-click in the Assets panel and choose New > UI Template. Name it, for example hud.html. The new file already holds a starter <template> to build on.
  2. In the Hierarchy, click Add Entity and pick UI Canvas.
  3. With the canvas selected, find UI Template in the Inspector and pick your file in the Template slot. (Or press + in the empty slot to create a new template named after the canvas, in your project's ui/ folder.)

The UI appears in the viewport. Open the template in the code editor, change some text, save, and the UI rebuilds straight away.

A selected UI Canvas in the Inspector, with a template in the UI Template slot

The UI workspace is set up for this: the hierarchy with the UI Widgets palette under it, the UI Editor and code editor in the middle, and the Inspector on the right. See Workspaces.

What a template looks like

A template is one <template> holding a tree of tags. Each tag becomes one box on screen. This is a small HUD with a title and a red health bar:

<template>
    <node
        position="absolute" top="24px" left="24px"
        flex_direction="column" row_gap="8px"
        padding="16px" width="280px"
        background="#11151C" border_radius="12px"
    >
        <text font_size="18" font_color="#FFFFFF">Vitals</text>
        <node width="100%" height="14px" background="#1B2233" border_radius="999px">
            <node name="health_fill" width="72%" height="100%" background="#E74C3C" border_radius="999px" />
        </node>
        <text name="score" font_size="14" font_color="#FFFFFF">Score: 0</text>
    </node>
</template>

The tags you will use most:

TagWhat it is
<node>A box. Your main building block for layout and backgrounds.
<text>Words on screen.
<image src="...">A picture from your project.
<button>Something the player can click.
<input>A text field the player can type into.
<icon name="...">A small icon.

Layout attributes work like CSS flexbox: flex_direction, align_items, justify_content, row_gap, padding, margin, width, height, position, top, left and so on. Sizes take px, % or auto. Every attribute needs a value in quotes (key="value").

Give a tag a name="..." and the box gets that name, which is how a script finds it later.

Hover and press styles

Prefix an attribute with hover: or pressed: to change it while the pointer is over the box or pressing it:

<button padding="10px 22px" border_radius="6px"
        background="#5B9CF5" hover:background="#7BB0FF" pressed:background="#2E9E5B">
    <text font_size="14" font_color="#FFFFFF">Play</text>
</button>

Showing live values

Put a value inside double braces and the text re-reads it every frame:

<text>Height: {{ Transform.translation.y }}</text>
<text>Player X: {{ Player.Transform.translation.x }}</text>
  • {{ Transform.translation.y }} reads a component on the canvas itself.
  • {{ Player.Transform.translation.x }} reads a component on the entity named Player.

The show attribute hides a box unless its condition is true:

<node show="{{ Player.Transform.translation.y < 0 }}" background="#E74C3C">
    <text>You fell!</text>
</node>

Conditions understand comparisons (<, >, <=, >=, ==, !=), and, or and not.

Changing the UI from a Rust script

Your script can change any box directly, because every tag is an ordinary entity. Find it by its name and write to it. New to scripts? Read Rust scripts first.

use bevy::prelude::*;

/// Set the text of the `<text name="...">` box called `name`.
fn set_text(world: &mut World, name: &str, value: &str) {
    let mut texts = world.query::<(&Name, &mut Text)>();
    for (n, mut text) in texts.iter_mut(world) {
        if n.as_str() == name {
            text.0 = value.to_string();
        }
    }
}

Then, in your script's update:

let score = 120;
set_text(ctx.world(), "score", &format!("Score: {score}"));

Buttons that do something

Give a button an on_press name. on_enter and on_exit fire when the pointer moves onto and off it.

<button name="btn_play" on_press="press_play" on_enter="hover_play">
    <text>Play</text>
</button>
<button name="btn_quit" on_press="press_quit">
    <text>Quit</text>
</button>

Your script hears these in its hooks function, as ScriptHook::Ui. Every script with a hooks function hears every UI event, so match on the name:

use bevy::prelude::*;
use renzora::{ScriptAction, ScriptCtx, ScriptHook};

fn update(_ctx: &mut ScriptCtx) {}

fn hooks(ctx: &mut ScriptCtx, hook: &ScriptHook) {
    match hook {
        ScriptHook::Ui { name, .. } => match *name {
            "press_play" => info!("Play pressed"),
            "press_quit" => {
                let me = ctx.entity();
                ScriptAction::new("quit", me).send(ctx.world());
            }
            _ => {}
        },
        _ => {}
    }
}

renzora::script!(update, hooks = hooks);

Driving an animation with no script

A button can poke an Animator directly. Instead of a callback name, write anim: followed by the animated entity's name and one of its parameters:

<button on_press="anim:hero.cheer">Cheer</button>
<button on_enter="anim:door.open=true" on_exit="anim:door.open=false">Open</button>

anim:hero.cheer fires the cheer trigger on the entity named hero. =true, =false or a number sets a parameter instead. Several names can share one event, separated by commas.

Showing and hiding whole screens

A script opens and closes templates with a few actions:

ActionArgumentsWhat it does
hui_spawntemplateOpens a template on a new UI Canvas.
hui_despawntemplate or nameCloses every canvas using that template, or the box with that name.
hui_hidenameHides the named box (and everything inside it).
hui_shownameShows it again.
quitCloses the game.
let me = ctx.entity();

// Open the pause menu.
ScriptAction::new("hui_spawn", me)
    .arg("template", "ui/pause_menu.html")
    .send(ctx.world());

// Hide the HUD while it is open.
ScriptAction::new("hui_hide", me)
    .arg("name", "hud_root")
    .send(ctx.world());

Hiding keeps the UI around, so showing it again is instant. Despawning removes it.

Canvas settings

Select a UI Canvas to see its settings:

FieldWhat it does
Sort OrderWhich canvas draws on top. Higher numbers draw over lower ones.
Visibilityalways, play_only (hidden while editing) or editor_only.
Ref Width / Ref HeightThe screen size you design for. Default 1280 x 720.
Scale ModeHow the design fits the real window (below).
Render Spacescreen for normal UI on top of the game, or world to show it on a flat panel in the 3D scene, placed by the canvas's transform.
Render ModeWorld canvases only: texture draws the UI onto the panel as an image, mesh builds it as geometry in the scene.

The UI Canvas component's fields in the Inspector

Scale modes

Players won't all have a 1280 x 720 window. Scale Mode decides what happens:

ModeWhat it doesGood for
fit (default)Scales your whole design to fit the window, centred, with empty bars on the spare sides. What you laid out is exactly what ships.Menus, dialogue, anything laid out by eye.
expandScales text and spacing, but lets the layout stretch to fill the window.A HUD whose corners should hug the screen edges.
constantNo scaling: one design pixel is one screen pixel.Pixel art that must stay crisp.

Building UI by dragging

Prefer clicking to typing? The UI Widgets palette has ready-made widgets (buttons, sliders, checkboxes, dropdowns, text inputs, progress bars, tooltips, pop-ups, shapes and more) that you drag onto a canvas in the UI Editor. Each one is an entity in your scene, edited in the Inspector, and saved with the scene.

Widgets always live under a UI Canvas. Drag one out of its canvas and the editor gives it a new canvas of its own rather than letting it escape. You can mix dragged widgets and templates freely, and have several canvases (a HUD and a pause menu, say).

The UI Widgets palette

Playing with a gamepad

Menus work with a controller with nothing to set up. The d-pad moves between buttons and the South button (A on Xbox, Cross on PlayStation) presses the focused one. Moving the mouse hands control back to the pointer.

For a screen that reads the gamepad itself, such as a gameplay HUD, turn this off so one press doesn't do two things:

if let Some(mut nav) = ctx.get_resource_mut::<renzora::ui::markup::gamepad_nav::UiGamepadNav>() {
    nav.enabled = false;
}

Exporting

When a game uses templates, the export includes the UI runtime automatically. See Exporting.