Lattice Workshop - Step 3.3

Add input system

Next step

To let players spawn by clicking on the map, let's add an input system. We'll use the input.click$ RxJS stream provided by the @latticexyz/phaser-middleware package. We transform the pixel coords to tile coords and use it to call the spawn method.

If you're not familiar with RxJS or want to dive deeper, check out the introduction at https://www.learnrxjs.io/

To text the input system, try clicking at any position on the map - you should see an entity popping up below your cursor.

Files changed (2) hide show
  1. client/src/Game.ts +2 -0
  2. client/src/systems/InputSystem.ts +21 -0
client/src/Game.ts CHANGED
@@ -19,6 +19,7 @@ import { createPositionSystem } from "./systems/PositionSystem";
19
19
  import { createTextureSystem } from "./systems/TextureSystem";
20
20
  import { createAppearanceSystem } from "./systems/AppearanceSystem";
21
21
  import { Coord } from "./types";
22
+ import { createInputSystem } from "./systems/InputSystem";
22
23
 
23
24
  export async function createGame(contractAddress: string, privateKey: string, chainId: number, personaId: number) {
24
25
  const world = createWorld();
@@ -104,6 +105,7 @@ export async function createGame(contractAddress: string, privateKey: string, ch
104
105
  createPositionSystem(context);
105
106
  createTextureSystem(context);
106
107
  createAppearanceSystem(context);
108
+ createInputSystem(context);
107
109
 
108
110
  return context;
109
111
  }
client/src/systems/InputSystem.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { Context } from "../types";
2
+ import { map, filter } from "rxjs";
3
+ import { pixelToWorldCoord } from "@latticexyz/phaser-middleware";
4
+
5
+ export function createInputSystem(context: Context) {
6
+ const {
7
+ phaser: { input, map: tilemap },
8
+ api: { spawn },
9
+ } = context;
10
+
11
+ input.click$
12
+ .pipe(
13
+ map((pointer) => ({ x: pointer.worldX, y: pointer.worldY })), // Map pointer to pointer pixel cood
14
+ map((pixel) => pixelToWorldCoord(tilemap, pixel)), // Map pixel coord to tile coord
15
+ filter((coord) => coord.x >= 0 && coord.y >= 0 && coord.x < tilemap.width && coord.y < tilemap.height) // Filter clicks outside the map
16
+ )
17
+ .subscribe((coord) => {
18
+ console.log("Spawn at", coord);
19
+ spawn(coord);
20
+ });
21
+ }