logo
By Lawrence

5 minutes

Score and Player Health

Right now you can clear wave after wave and nothing changes. No number goes up when an enemy falls, and an enemy that walks up to your ship stops and waits. You shoot targets, but nothing is on the line. Two small changes fix that: a reason to keep shooting, and a cost for letting enemies get close.

The scoreboard and points per kill

The game keeps score on one new entity. Add it to the running scene:

src/scenes/TwinStickArena.json
"ScoreState": {
  "components": {
    "Score": { "defaultPoints": 100, "scores": { "Player": 0 } }
  }
}

That one Score component on one entity is the only scene change in this lesson. defaultPoints: 100 is the score you give when no one names a value, and scores: { Player: 0 } starts the player's total at zero. Nothing else in the scene names ScoreState — the Score system finds it on its own and treats it as the one scoreboard as soon as the world loads.

The scorekeeping is plain math. No 3D shows up in it at all:

src/components/Score/Score.core.ts
export function createScore(
  params: Partial<ScoreParams> = {},
  initialScores: Record<string, number> = {},
): ScoreInstance {
  const active: ScoreParams = { ...DEFAULT_SCORE_PARAMS, ...params };
  const scores = new Map<string, number>();
  for (const [id, value] of Object.entries(initialScores)) {
    scores.set(id, clamp(value, active.minScore, active.maxScore));
  }

  return {
    addScore(ownerEntity, points) {
      const from = scores.get(ownerEntity) ?? 0;
      const delta = points ?? active.defaultPoints;
      const to = clamp(from + delta, active.minScore, active.maxScore);
      scores.set(ownerEntity, to);
      return { ownerEntity, from, to, delta: to - from };
    },

addScore takes an owner id and an optional point value. It reads the current total, adds the points, and returns a record of the before and after:

Continue reading

Unlock the Full Course

Every lesson, the runnable examples, and the finished build — yours to keep.

$9one-time

Was this page helpful?

We read every note — tell us what's working and what isn't.

↑↓ NavigateEnter SelectEsc CloseCtrl+K Open Search