Molten

Step 3: Collecting coins and a HUD

The player can walk; now coins disappear when touched, the score goes up, and a HUD shows it.

Picking coins up

// behaviors/pickup.cast
import { behavior, placedObject, Transform } from "molten";
import { Coin } from "../components/coin";

// Collects a coin when the player walks into it.
export default behavior([Transform, Coin], (objects, dt: float): void => {
    const director = placedObject("director").as<Director>()?.get();
    if (!director) return;
    const player = director.coinGame.player.as<Player>()?.get();
    if (!player) return;
    const chest = player.transform.position + vec3(0, 1, 0);
    let gained = 0;
    for (const obj of objects) {
        if (distance(obj.transform.position, chest) < 1.2) {
            gained += obj.coin.value;
            obj.destroy();
        }
    }
    // Narrowing does not carry across a loop, so test director again.
    if (director && gained > 0) director.coinGame.score += gained;
});
  • placedObject("director") finds an object the level placed, by its id.
  • .as<Director>() works because every .object file is also a Cast type: Director, Player, Coin. No import is needed.
  • obj.destroy() is deferred: the coin stays valid until the end of the tick, so the loop is never disturbed.
  • director.coinGame.score += gained writes straight into the director's component.

Why test director again? Cast checks null with flow analysis like TypeScript, but it forgets what it learned when a loop starts or ends. Using director inside or after the loop needs a fresh check. Without it, castc reports nullable receiver must be narrowed before member access.

Move the first coin onto the spawn point so you see the score change right away:

// levels/yard/chunks/0_0.chunk
export default chunk({
    format: "chunk-local-v1",
    coord: [0, 0],
    objects: [
        { id: "ground", type: Ground },
        { id: "director", type: Director },
        { id: "coin-1", type: Coin, position: vec3(0, 1, 6) },
        { id: "coin-2", type: Coin, position: vec3(-4, 1, -3) },
        { id: "coin-3", type: Coin, position: vec3(5, 1, -6), overrides: { coin: { value: 5 } } },
    ],
});

Publishing values for the UI

UI files never run gameplay code. Instead, Cast publishes named values, and the UI reads them by name every frame:

// behaviors/hud.cast
import { behavior, uiSetNumber, uiSetText } from "molten";
import { CoinGame } from "../components/coin_game";

// Publishes the values the HUD binds to.
export default behavior([CoinGame], (objects, dt: float): void => {
    for (const obj of objects) {
        const game = obj.coinGame;
        uiSetText("hud.score", `Score ${game.score} / ${game.goal}`);
        uiSetNumber("hud.points", game.score);
        uiSetNumber("hud.goal", game.goal);
        uiSetText("hud.message", game.score >= game.goal ? "All coins found!" : "Find the coins");
    }
});

Here const game = obj.coinGame is fine: the code only reads it. Backtick strings with ${...} build text from numbers and strings.

Each name holds one value. If you publish hud.score as text and then as a number, the number wins and the text binding shows 1. Use a different name for each.

The HUD

// ui/hud.ui
export default ui(
    <panel class="hud">
        <text class="title">{hud.score}</text>
        <progress id="progress" class="bar" value={hud.points} max={hud.goal} />
        <text id="message">{hud.message}</text>
    </panel>
);
/* ui/hud.style */
.hud {
    position: absolute;
    left: 24px;
    top: 24px;
    width: 240px;
    padding: 14px;
    flex-direction: column;
    gap: 8px;
    background: #141e2bdd;
    border-radius: 10px;
    color: #e5edf6;
    font-size: 16px;
}
.title { font-size: 22px; color: #ffd76a; }
.bar { width: 212px; height: 12px; color: #ffd76a; background: #2a3646; }
  • A .ui file is a JSX-style tree of widgets. {hud.score} binds to the value published under that name.
  • The .style file next to it is a CSS subset: flexbox and grid layout, pixels and percentages, colors, borders and radius, and transitions. See .style files.

Show the HUD on the Playing screen:

// screens/playing.screen
// The screen the game starts on. It loads the "yard" level and shows the HUD.
export default screen({
    level: "yard",
    ui: ["ui/hud"],
});

Run it

The HUD reads Score 1 / 7 at once (coin-1 sits on the spawn point). Walk into the other coins to reach 7.

Things to try while it runs:

  • Edit hud.style (for example the .title color). The HUD restyles without losing its state.
  • Break it on purpose: write font-size: 22pt;. The console prints ui/hud.style:14:10: error: invalid CSS declaration 'font-size' and the old style stays.

Next: sound and music.

View this page's source on GitHub