Lattice Workshop - Step 6.2

Add lifebar

Next step

To visualize the health of entities, we'll add a simple lifebar using the drawBar utility provided by @latticexyz/phaser-middleware.

Files changed (2) hide show
  1. client/src/Game.ts +2 -0
  2. client/src/systems/LifeSystem.ts +36 -0
client/src/Game.ts CHANGED
@@ -21,6 +21,7 @@ import { createAppearanceSystem } from "./systems/AppearanceSystem";
21
21
  import { Coord } from "./types";
22
22
  import { createInputSystem } from "./systems/InputSystem";
23
23
  import { Directions } from "./constants";
24
+ import { createLifeSystem } from "./systems/LifeSystem";
24
25
 
25
26
  export async function createGame(contractAddress: string, privateKey: string, chainId: number, personaId: number) {
26
27
  const world = createWorld();
@@ -133,6 +134,7 @@ export async function createGame(contractAddress: string, privateKey: string, ch
133
134
  createTextureSystem(context);
134
135
  createAppearanceSystem(context);
135
136
  createInputSystem(context);
137
+ createLifeSystem(context);
136
138
 
137
139
  return context;
138
140
  }
client/src/systems/LifeSystem.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { defineReactionSystem, defineUpdateQuery, getComponentValue, Has } from "@latticexyz/mobx-ecs";
2
+ import { drawBar, worldCoordToPixelTopLeft } from "@latticexyz/phaser-middleware";
3
+ import { Context } from "../types";
4
+
5
+ export function createLifeSystem(context: Context) {
6
+ const {
7
+ world,
8
+ components: { Life, Position },
9
+ phaser: { map, graphicsPool },
10
+ } = context;
11
+
12
+ const lifePositionQuery = defineUpdateQuery(world, [Has(Life), Has(Position)]);
13
+ defineReactionSystem(
14
+ world,
15
+ () => lifePositionQuery.get(),
16
+ async (entities) => {
17
+ for (const entity of entities) {
18
+ const life = getComponentValue(Life, entity);
19
+ const coord = getComponentValue(Position, entity);
20
+
21
+ // Remove lifebar if the entity has no life or position anymore
22
+ if (!life || !coord) {
23
+ graphicsPool.remove(entity);
24
+ return;
25
+ }
26
+
27
+ // Render life bar
28
+ const pixelCoord = worldCoordToPixelTopLeft(map, coord);
29
+ const lifebar = graphicsPool.get(entity);
30
+ lifebar.setDepth(5);
31
+ drawBar(lifebar, life.value1, life.value2, map.tileWidth, 0xeb4926);
32
+ lifebar.setPosition(pixelCoord.x, pixelCoord.y + 2);
33
+ }
34
+ }
35
+ );
36
+ }