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.castfile. 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. objectsholds every object with all the listed components. Each component is a field named in lowerCamelCase:Healthisobj.health,NavAgentisobj.navAgent. Writingobj.health.current = ...writes straight into engine memory.obj.handleis the object'sHandle<Object>;obj.destroy()destroys it at the end of the tick.dtis the fixed tick length in seconds (1/60 by default;molten-game --sim-hz Nchanges 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:
- Behaviors run in registration order. Cast registers them in alphabetical order of
their file path (
behaviors/directorbeforebehaviors/hud), so name files to order them if it matters. - Deferred changes land: spawns, destroys, added and removed components, screen switches and level loads.
- 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
letis a compile error; put state in components, or in classstaticfields (stored in engine game memory). - Hold an object across ticks except by handle.
- Capture
objectsorobjin an arrow function (their handles can be captured).