Molten

Step 2: A player you can walk

Levels never contain the player: a level is a place, and the player arrives when the game starts playing. In this step a placed director object spawns the player at the level's spawn point and moves it with WASD.

The round's state

Gameplay code may not keep state in global variables: the code is swapped on every save, and only engine memory survives. State lives in components. This one holds the round:

// components/coin_game.cast
// The state of one round. It lives on the placed "director" object,
// so it is engine memory: it survives code reloads.
@component
export struct CoinGame {
    @group("Rules") goal: int = 7;
    @group("Rules") walkSpeed: float = 5;
    @readonly score: int = 0;
    @hidden player: Handle<Object>;
    @hidden started: bool = false;
}
  • Handle<Object> is a reference to an object in the world. Handles are plain values you can store in components and keep across frames and reloads. A handle to a destroyed object resolves to null instead of dangling.
  • @group groups fields in the editor's Inspector, @readonly shows a field without letting the Inspector edit it, @hidden hides it from the Inspector (it is still saved).

The director is an object type with only that component:

// objects/director.object
// An invisible object that holds the round's state.
export default object({
    coinGame: {},
});

coinGame: {} adds the component with its defaults.

The player and its parts

// objects/player.object
// A walking capsule. Its origin is at its feet; the body part is lifted
// so the box sits on the ground, and the camera part follows behind.
export default object({
    characterController: { height: 1.8, radius: 0.35, speed: 6 },
    parts: {
        body: { type: PlayerBody, position: vec3(0, 0.9, 0) },
        camera: { type: ViewCamera, position: vec3(0, 6, 9), rotation: euler(-30, 0, 0) },
    },
});
// objects/player_body.object
export default object({
    mesh: { mesh: "models/cube.gltf", color: vec4(0.3, 0.6, 1, 1) },
    transform: { scale: vec3(0.7, 1.8, 0.7) },
});
  • characterController gives the player a physics capsule that walks, climbs small steps and collides with the world. Its origin is at the feet.
  • Parts are other objects attached to this one. Their position and rotation are relative to the owner, they move with it, and they are destroyed with it. The camera that used to be placed in the level is now a part of the player, so it follows them.

The capsule needs something solid to stand on. Give the ground a collider:

// objects/ground.object
// A wide, flat box for everything to stand on. The collider makes it solid.
export default object({
    mesh: { mesh: "models/cube.gltf", color: vec4(0.35, 0.55, 0.3, 1) },
    transform: { position: vec3(0, -0.5, 0), scale: vec3(30, 1, 30) },
    collider: {},
});

A collider with no rigidBody is static. Its default shape is a 1 m box, scaled by the object's scale.

The director behavior

// behaviors/director.cast
import { behavior, characterMove, Key, keyDown, spawnObject, spawnPosition } from "molten";
import { CoinGame } from "../components/coin_game";

function axis(positive: Key, negative: Key): float {
    return (keyDown(positive) ? 1 : 0) - (keyDown(negative) ? 1 : 0);
}

export default behavior([CoinGame], (objects, dt: float): void => {
    for (const obj of objects) {
        // Write through obj.coinGame: `const game = obj.coinGame` would be a copy.
        if (!obj.coinGame.started) {
            obj.coinGame.player = spawnObject("Player", spawnPosition(0));
            obj.coinGame.started = true;
        }
        const player = obj.coinGame.player.as<Player>()?.get();
        if (!player) continue;
        let direction = vec3(axis("D", "A"), 0, axis("S", "W"));
        if (length(direction) > 0) direction = normalize(direction);
        characterMove(player.handle, direction * obj.coinGame.walkSpeed, false);
    }
});

Line by line:

  • spawnObject("Player", spawnPosition(0)) creates a Player (with its parts) at the first spawn point and returns its handle. Objects spawned while a level is loaded belong to that level and are destroyed when it unloads.
  • obj.coinGame.player.as<Player>() checks that the handle points at a live Player and gives a Handle<Player> | null. ?.get() then gives the Player itself, or null. Cast makes you check for null before you use it: that is if (!player) continue;.
  • A Player value has a field for each component its .object file lists, plus transform and handle.
  • characterMove(object, velocity, jump) asks the character controller to walk at that horizontal velocity during the next physics tick (capped at its speed). Call it every tick.
  • Key names physical keyboard positions. "W" is the key where W sits on a US layout. See the input reference for all key names.

Watch out: component structs are values. const game = obj.coinGame; makes a copy. Writing game.started = true would change the copy, not the object, and the player would be spawned again every tick. Write through obj.coinGame.started. Reading through a copy is fine.

Space also toggles simulation pause in dev-link builds. The tutorial binds jump to a separate key so you can test it while running the dev build.

Place the director

Replace the camera in the chunk with the director:

// 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, 0) },
        { id: "coin-2", type: Coin, position: vec3(-4, 1, -3) },
        { id: "coin-3", type: Coin, position: vec3(5, 1, -6), overrides: { coin: { value: 5 } } },
    ],
});

Run it

castc check coinyard prints 6 objects, 1 screen, 1 level. Run the game: a blue box stands at the spawn point and walks with WASD; the camera follows.

Try this while it runs: open the game in devtools (F5 from dev-run), select director and change walkSpeed in the Inspector. It takes effect at once. Save to file writes it into the chunk as an override.

Next: collecting coins and a HUD.

View this page's source on GitHub