Editor documentation

Now, let’s put the control over the blobs back in the hands of players.

Add the following callback into your game script from the previous chapter:

Player.onSteer = (player: Player, dir: number) => {
  blob.dir = dir
}

You may see that the editor is smart enough to sense that something isn’t right about the blob part there and indicates that by underlining it in red. Let’s ignore that for a sec and play the script. You’ll once again see the blob moving south, but once you move the mouse (or use any other input method) the game will immediately stop and you’ll be back in the editor with an error alert.

What happened? Our intent was to set the blob’s dir property to the dir with player input. Everything seems legit yet the game failed.

It’s time to meet the Errors pane. Toggle it from the toolbar to see the list of errors, with latest entries on top. There, you’ll see our error: ReferenceError: blob is not defined. Click it to expand details with a link game.ts:L:C that allows to jump straight to the involved line & column.

And there it is. We’re assigning to non-existent variable blob, which is right since we’ve defined blob as a local variable in the Player.onJoin callback so the Player.onSteer callback is clueless about it. Furthermore, both callbacks may be called by multiple players so a single variable won’t do. Note how you could anticipate such problems even before running the code by inspecting problems reported by the editor.

To fix it, add the following at the top, just below the imports:

const playerBlobs: { [key: string]: Blob } = {}

And then edit the player callbacks like shown below:

Player.onJoin = (player: Player) => {
  // ...

  playerBlobs[player.id] = blob
}

Player.onSteer = (player: Player, dir: number) => {
  playerBlobs[player.id].dir = dir
}

Here’s the general idea:

  1. We define the playerBlobs map to hold each player’s blob, mapped by player’s id.

  2. We store each player’s blob in the map after creating it.

  3. We look it up to set the dir property and update the direction.

Play the game to finally enjoy taking control of your blob. As always, be sure to try with another player or in second browser window to check that things work just as well in multiplayer.

While at it, let’s make a final touch on the controls by adding the following callback:

Player.onAction = (player, enabled) => {
  playerBlobs[player.id].speed = enabled ? 20 : 5
}

This will allow you to boost by holding the mouse — a nice game mechanics and a useful trick for further testing.

Next chapter: Collisions.