Molten

Behaviors

A behavior is code that runs every simulation tick on every object that has a given set of components. It is the main place gameplay code lives.

// behaviors/health.cast (from samples/farmhouse)
import { behavior, uiSetNumber } from "molten";
import { Health } from "../components/health";

export default behavior([Health], (objects, dt: float): void => {
    for (const obj of objects) {
        obj.health.current = min(obj.health.max, obj.health.current + obj.health.regen * dt);
        if (obj.handle.as<Player>()) {
            uiSetNumber("player.health.current", obj.health.current);
            uiSetNumber("player.health.max", obj.health.max);
        }
        if (obj.health.current <= 0) obj.destroy();
    }
});

The rules

  • A behavior is the export default behavior([...], callback) of a .cast file. One per file. Its name is the file path without the extension (behaviors/health), which is how devtools shows it.
  • The list needs at least one component. Built-in components (Transform, Mesh, ...) must be imported from "molten", your own from their module.
  • objects holds every object with all the listed components. Each component is a field named in lowerCamelCase: Health is obj.health, NavAgent is obj.navAgent. Writing obj.health.current = ... writes straight into engine memory.
  • obj.handle is the object's Handle<Object>; obj.destroy() destroys it at the end of the tick.
  • dt is the fixed tick length in seconds (1/60 by default; molten-game --sim-hz N changes it).
  • The compiler turns the loop into a plain C loop over component storage, with no call into the engine per object.

When behaviors run

Each simulation tick:

  1. Behaviors run in registration order. Cast registers them in alphabetical order of their file path (behaviors/director before behaviors/hud), so name files to order them if it matters.
  2. Deferred changes land: spawns, destroys, added and removed components, screen switches and level loads.
  3. Physics steps.

Pausing through devtools or through Space in a dev-link build stops simulation ticks and behaviors. Rendering, UI and live reload keep working. Behaviors run whichever screen is on top. Use screenIs(...) to limit a behavior to a particular screen.

A behavior as the game's "manager"

Behaviors only run on objects, so game-wide logic needs an object to run on. The common pattern, used by Gridline and the tutorial: place one object (dispatch, director) whose type has a state component, and write a behavior over that component. It can spawn the player, publish the HUD and switch screens.

Things a behavior can't do

  • Keep state in variables between ticks. Module-level let is a compile error; put state in components, or in class static fields (stored in engine game memory).
  • Hold an object across ticks except by handle.
  • Capture objects or obj in an arrow function (their handles can be captured).

View this page's source on GitHub