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 tonullinstead of dangling.@groupgroups fields in the editor's Inspector,@readonlyshows a field without letting the Inspector edit it,@hiddenhides 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) },
});
characterControllergives 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 aPlayer(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 livePlayerand gives aHandle<Player> | null.?.get()then gives thePlayeritself, ornull. Cast makes you check fornullbefore you use it: that isif (!player) continue;.- A
Playervalue has a field for each component its.objectfile lists, plustransformandhandle. characterMove(object, velocity, jump)asks the character controller to walk at that horizontal velocity during the next physics tick (capped at itsspeed). Call it every tick.Keynames 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. Writinggame.started = truewould change the copy, not the object, and the player would be spawned again every tick. Write throughobj.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.