Lattice Workshop - Step 6.5

Add colors based on owner

Next step

To be able to distinguish different players better, we add a OwnedBySystem that tints every game object in a color generated from their OwnedBy component value. For this we can use the getPlayerColor utility provided by @latticexyz/phaser-middleware.

Files changed (2) hide show
  1. client/src/Game.ts +2 -0
  2. client/src/systems/OwnedBySystem.ts +40 -0
client/src/Game.ts CHANGED
@@ -31,6 +31,7 @@ import { createInputSystem } from "./systems/InputSystem";
31
31
  import { Directions } from "./constants";
32
32
  import { createLifeSystem } from "./systems/LifeSystem";
33
33
  import { createParticleSystem } from "./systems/ParticleSystem";
34
+ import { createOwnedBySystem } from "./systems/OwnedBySystem";
34
35
 
35
36
  export async function createGame(contractAddress: string, privateKey: string, chainId: number, personaId: number) {
36
37
  const world = createWorld();
@@ -161,6 +162,7 @@ export async function createGame(contractAddress: string, privateKey: string, ch
161
162
  createInputSystem(context);
162
163
  createLifeSystem(context);
163
164
  createParticleSystem(context);
165
+ createOwnedBySystem(context);
164
166
 
165
167
  return context;
166
168
  }
client/src/systems/OwnedBySystem.ts ADDED
@@ -0,0 +1,40 @@
1
+ import { defineReactionSystem, defineUpdateQuery, getComponentValue, Has, Not } from "@latticexyz/mobx-ecs";
2
+ import { getPlayerColor } from "@latticexyz/phaser-middleware";
3
+ import { Context } from "../types";
4
+
5
+ export function createOwnedBySystem(context: Context) {
6
+ const {
7
+ world,
8
+ components: { OwnedBy, Appearance },
9
+ phaser: { objectPool },
10
+ } = context;
11
+
12
+ const ownedEntities = defineUpdateQuery(world, [Has(Appearance), Has(OwnedBy)]);
13
+ const notOwnedEntities = defineUpdateQuery(world, [Has(Appearance), Not(OwnedBy)]);
14
+
15
+ defineReactionSystem(
16
+ world,
17
+ () => ownedEntities.get(),
18
+ (entities) => {
19
+ for (const entity of entities) {
20
+ const ownedBy = getComponentValue(OwnedBy, entity);
21
+ const appearance = getComponentValue(Appearance, entity);
22
+ if (!ownedBy || !appearance) return;
23
+
24
+ const object = objectPool.get(entity);
25
+ object.tint = getPlayerColor(String(ownedBy.value));
26
+ }
27
+ }
28
+ );
29
+
30
+ defineReactionSystem(
31
+ world,
32
+ () => notOwnedEntities.get(),
33
+ (entities) => {
34
+ for (const entity of entities) {
35
+ const object = objectPool.get(entity);
36
+ object.tint = 0x404040;
37
+ }
38
+ }
39
+ );
40
+ }