Lattice Workshop - Step 6.8

Highlight the selected entity

Next step

To make it more obvious to the player which entity is selected, add a simple box highlighting the currently selected entity.

For this purpose we add a SelectedSystem that queries for the entity with the Selected component and draws a tile using the drawTile utility at the entitiy's location.

Files changed (2) hide show
  1. client/src/Game.ts +2 -0
  2. client/src/systems/SelectedSystem.ts +35 -0
client/src/Game.ts CHANGED
@@ -32,6 +32,7 @@ import { Directions } from "./constants";
32
32
  import { createLifeSystem } from "./systems/LifeSystem";
33
33
  import { createParticleSystem } from "./systems/ParticleSystem";
34
34
  import { createOwnedBySystem } from "./systems/OwnedBySystem";
35
+ import { createSelectedSystem } from "./systems/SelectedSystem";
35
36
 
36
37
  export async function createGame(contractAddress: string, privateKey: string, chainId: number, personaId: number) {
37
38
  const world = createWorld();
@@ -163,6 +164,7 @@ export async function createGame(contractAddress: string, privateKey: string, ch
163
164
  createLifeSystem(context);
164
165
  createParticleSystem(context);
165
166
  createOwnedBySystem(context);
167
+ createSelectedSystem(context);
166
168
 
167
169
  return context;
168
170
  }
client/src/systems/SelectedSystem.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { defineReactionSystem, defineUpdateQuery, getComponentValue, Has } from "@latticexyz/mobx-ecs";
2
+ import { drawTile, worldCoordToPixelTopLeft } from "@latticexyz/phaser-middleware";
3
+ import { Context } from "../types";
4
+
5
+ export function createSelectedSystem(context: Context) {
6
+ const {
7
+ world,
8
+ components: { Selected, Position },
9
+ phaser: { map, graphicsPool },
10
+ } = context;
11
+
12
+ const selectedQuery = defineUpdateQuery(world, [Has(Selected), Has(Position)]);
13
+ defineReactionSystem(
14
+ world,
15
+ () => selectedQuery.get(),
16
+ async (entities) => {
17
+ for (const entity of entities) {
18
+ const coord = getComponentValue(Position, entity);
19
+
20
+ if (!coord) {
21
+ graphicsPool.remove("selection");
22
+ return;
23
+ }
24
+
25
+ // Render life bar
26
+ const pixelPosition = worldCoordToPixelTopLeft(map, coord);
27
+
28
+ const selection = graphicsPool.get("selection");
29
+ selection.setDepth(1);
30
+ drawTile(selection, map.tileWidth);
31
+ selection.setPosition(pixelPosition.x, pixelPosition.y);
32
+ }
33
+ }
34
+ );
35
+ }