A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(game): a room, two wisps, and one path from a swing to a death
esenginea858bab9fc97
diff --git a/desktop/scripts/inputScript.mjs b/desktop/scripts/inputScript.mjsindex 79698443c..a9cc05b0b 100644--- a/desktop/scripts/inputScript.mjs+++ b/desktop/scripts/inputScript.mjs@@ -15,12 +15,24 @@/*** JS source that plays `spec` and then lets the game run on.- * `{ keys?: string[], pointer?: { x, y, action? }, frames?: number }`+ * `{ keys?, pointer?, frames?, taps?: [{key, at}], holds?: [{key, from, to}] }`+ *+ * `keys` hold for the whole run, `taps` press at a frame index, `holds` hold over+ * a frame range. A playthrough is a sequence, not a posture: "walk there, turn+ * round, hit it" cannot be said by keys all pressed at frame zero.*/export function inputScript(spec) {const keys = JSON.stringify(spec.keys ?? []);const pointer = JSON.stringify(spec.pointer ?? null);const frames = Number(spec.frames ?? 40);+ const taps = JSON.stringify(+ (spec.taps ?? []).map((t) => ({ key: String(t.key), at: Number(t.at) || 0 })),+ );+ const holds = JSON.stringify(+ (spec.holds ?? []).map((h) => ({+ key: String(h.key), from: Number(h.from) || 0, to: Number(h.to ?? frames),+ })),+ );return `(async () => {const raf = () => new Promise((r) => requestAnimationFrame(r));@@ -58,10 +70,28 @@ export function inputScript(spec) {for (let i = 0; i < 4; i++) await raf();firePointer('up', pointer.x, pointer.y);}- for (let i = 0; i < ${frames}; i++) await raf();+ const taps = ${taps};+ const holds = ${holds};+ const down = new Set();+ for (let i = 0; i < ${frames}; i++) {+ for (const h of holds) {+ if (h.from === i) { fireKey('keydown', h.key); down.add(h.key); }+ if (h.to === i && down.has(h.key)) { fireKey('keyup', h.key); down.delete(h.key); }+ }+ for (const t of taps) {+ if (t.at !== i) continue;+ fireKey('keydown', t.key);+ // Held a couple of frames for the same reason a pointer press is:+ // a key sampled once per frame can land between two of them.+ for (let j = 0; j < 2; j++) await raf();+ fireKey('keyup', t.key);+ }+ await raf();+ }+ for (const k of down) fireKey('keyup', k);for (const k of keys) fireKey('keyup', k);await raf();- return keys.length + (pointer ? 1 : 0);+ return keys.length + taps.length + holds.length + (pointer ? 1 : 0);})()`;}diff --git a/examples/celestial-heights/assets/ai/wisp.esbt b/examples/celestial-heights/assets/ai/wisp.esbtnew file mode 100644index 000000000..66d6d9def--- /dev/null+++ b/examples/celestial-heights/assets/ai/wisp.esbt@@ -0,0 +1,31 @@+{+ "root": {+ "type": "selector",+ "id": "n0",+ "x": 60,+ "y": 170,+ "children": [+ {+ "type": "sequence",+ "id": "n1",+ "x": 300,+ "y": 60,+ "children": [+ { "type": "condition", "id": "n2", "name": "inStrikeRange", "x": 560, "y": 20 },+ { "type": "action", "id": "n3", "name": "strike", "x": 560, "y": 100 }+ ]+ },+ {+ "type": "sequence",+ "id": "n4",+ "x": 300,+ "y": 200,+ "children": [+ { "type": "condition", "id": "n5", "name": "seesPlayer", "x": 560, "y": 160 },+ { "type": "action", "id": "n6", "name": "chase", "x": 560, "y": 240 }+ ]+ },+ { "type": "action", "id": "n7", "name": "hover", "x": 300, "y": 330 }+ ]+ }+}diff --git a/examples/celestial-heights/assets/ai/wisp.esbt.meta b/examples/celestial-heights/assets/ai/wisp.esbt.metanew file mode 100644index 000000000..a48b3acf7--- /dev/null+++ b/examples/celestial-heights/assets/ai/wisp.esbt.meta@@ -0,0 +1,6 @@+{+ "uuid": "f0c376f0-8671-412c-99a0-749b39644343",+ "version": "1.0",+ "type": "behaviortree",+ "importer": { "autoMigrate": true }+}diff --git a/examples/celestial-heights/assets/scenes/main.esscene b/examples/celestial-heights/assets/scenes/main.essceneindex 2726be4f5..e55b0bae0 100644--- a/examples/celestial-heights/assets/scenes/main.esscene+++ b/examples/celestial-heights/assets/scenes/main.esscene@@ -22,7 +22,7 @@"folder": "Environment","components": [{ "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },- { "type": "Sprite", "data": { "size": { "x": 1920, "y": 1080 }, "color": { "r": 0.106, "g": 0.09, "b": 0.169, "a": 1 }, "layer": -20 } }+ { "type": "Sprite", "data": { "size": { "x": 1600, "y": 900 }, "color": { "r": 0.106, "g": 0.09, "b": 0.169, "a": 1 }, "layer": 0 } }],"visible": true},@@ -34,20 +34,175 @@"folder": "Environment","components": [{ "type": "Transform", "data": { "position": { "x": 0, "y": -120, "z": 0 } } },- { "type": "Sprite", "data": { "size": { "x": 1400, "y": 260 }, "color": { "r": 0.192, "g": 0.169, "b": 0.263, "a": 1 }, "layer": -10 } }+ { "type": "Sprite", "data": { "size": { "x": 1200, "y": 260 }, "color": { "r": 0.192, "g": 0.169, "b": 0.263, "a": 1 }, "layer": 1 } }],"visible": true},{- "id": 3,+ "id": 10,+ "name": "Wall_North",+ "parent": null,+ "children": [],+ "folder": "Environment",+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 470, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 1680, "y": 40 }, "color": { "r": 0.267, "g": 0.235, "b": 0.361, "a": 1 }, "layer": 2 } },+ { "type": "RigidBody", "data": { "bodyType": 0 } },+ { "type": "BoxCollider", "data": { "halfExtents": { "x": 8.4, "y": 0.2 }, "categoryBits": 1, "maskBits": 65535 } }+ ],+ "visible": true+ },+ {+ "id": 11,+ "name": "Wall_South",+ "parent": null,+ "children": [],+ "folder": "Environment",+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": -470, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 1680, "y": 40 }, "color": { "r": 0.267, "g": 0.235, "b": 0.361, "a": 1 }, "layer": 2 } },+ { "type": "RigidBody", "data": { "bodyType": 0 } },+ { "type": "BoxCollider", "data": { "halfExtents": { "x": 8.4, "y": 0.2 }, "categoryBits": 1, "maskBits": 65535 } }+ ],+ "visible": true+ },+ {+ "id": 12,+ "name": "Wall_West",+ "parent": null,+ "children": [],+ "folder": "Environment",+ "components": [+ { "type": "Transform", "data": { "position": { "x": -820, "y": 0, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 40, "y": 940 }, "color": { "r": 0.267, "g": 0.235, "b": 0.361, "a": 1 }, "layer": 2 } },+ { "type": "RigidBody", "data": { "bodyType": 0 } },+ { "type": "BoxCollider", "data": { "halfExtents": { "x": 0.2, "y": 4.7 }, "categoryBits": 1, "maskBits": 65535 } }+ ],+ "visible": true+ },+ {+ "id": 13,+ "name": "Wall_East",+ "parent": null,+ "children": [],+ "folder": "Environment",+ "components": [+ { "type": "Transform", "data": { "position": { "x": 820, "y": 0, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 40, "y": 940 }, "color": { "r": 0.267, "g": 0.235, "b": 0.361, "a": 1 }, "layer": 2 } },+ { "type": "RigidBody", "data": { "bodyType": 0 } },+ { "type": "BoxCollider", "data": { "halfExtents": { "x": 0.2, "y": 4.7 }, "categoryBits": 1, "maskBits": 65535 } }+ ],+ "visible": true+ },+ {+ "id": 20,"name": "Lyra_Player","parent": null,"children": [],"folder": "Actors","components": [- { "type": "Transform", "data": { "position": { "x": 0, "y": -90, "z": 0 } } },- { "type": "Sprite", "data": { "size": { "x": 84, "y": 150 }, "color": { "r": 0.855, "g": 0.788, "b": 0.976, "a": 1 }, "layer": 10 } },- { "type": "Player", "data": {} }+ { "type": "Transform", "data": { "position": { "x": -260, "y": -90, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 84, "y": 150 }, "color": { "r": 0.855, "g": 0.788, "b": 0.976, "a": 1 }, "layer": 2 } },+ { "type": "Player", "data": { "speed": 380 } },+ { "type": "Facing", "data": { "x": 1, "y": 0 } },+ { "type": "Health", "data": { "current": 120, "max": 120, "invulnerability": 0.5, "invulnerable": 0 } },+ { "type": "MeleeAttack", "data": { "damage": 30, "reach": 110, "arcDegrees": 120, "cooldown": 0.4, "cooldownLeft": 0, "pending": false, "hits": 4 } },+ { "type": "PerceptionTarget", "data": {} },+ { "type": "RigidBody", "data": { "bodyType": 1 } },+ { "type": "CircleCollider", "data": { "radius": 0.3, "offset": { "x": 0, "y": -0.5 }, "categoryBits": 2, "maskBits": 1 } },+ { "type": "CharacterController", "data": { "up": { "x": 0, "y": 1 }, "snapLength": 0, "maskBits": 1 } }+ ],+ "visible": true+ },+ {+ "id": 30,+ "name": "Wisp_A",+ "parent": null,+ "children": [300, 301],+ "folder": "Actors",+ "components": [+ { "type": "Transform", "data": { "position": { "x": 320, "y": 150, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 64, "y": 96 }, "color": { "r": 0.412, "g": 0.812, "b": 0.902, "a": 1 }, "layer": 2 } },+ { "type": "Enemy", "data": {} },+ { "type": "Facing", "data": { "x": -1, "y": 0 } },+ { "type": "Health", "data": { "current": 60, "max": 60, "invulnerability": 0.2, "invulnerable": 0 } },+ { "type": "MeleeAttack", "data": { "damage": 12, "reach": 76, "arcDegrees": 160, "cooldown": 1.2, "cooldownLeft": 0, "pending": false, "hits": 2 } },+ { "type": "Perceiver", "data": { "range": 380, "fovDegrees": 360 } },+ { "type": "NavAgent", "data": { "speed": 150, "arriveRadius": 48, "repathInterval": 0.35 } },+ { "type": "BehaviorTreeAgent", "data": { "bt": "assets/ai/wisp.esbt" } },+ { "type": "RigidBody", "data": { "bodyType": 1 } },+ { "type": "CircleCollider", "data": { "radius": 0.26, "offset": { "x": 0, "y": -0.3 }, "categoryBits": 4, "maskBits": 1 } }+ ],+ "visible": true+ },+ {+ "id": 31,+ "name": "Wisp_B",+ "parent": null,+ "children": [310, 311],+ "folder": "Actors",+ "components": [+ { "type": "Transform", "data": { "position": { "x": 460, "y": -220, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 64, "y": 96 }, "color": { "r": 0.522, "g": 0.729, "b": 0.976, "a": 1 }, "layer": 2 } },+ { "type": "Enemy", "data": {} },+ { "type": "Facing", "data": { "x": -1, "y": 0 } },+ { "type": "Health", "data": { "current": 60, "max": 60, "invulnerability": 0.2, "invulnerable": 0 } },+ { "type": "MeleeAttack", "data": { "damage": 12, "reach": 76, "arcDegrees": 160, "cooldown": 1.4, "cooldownLeft": 0, "pending": false, "hits": 2 } },+ { "type": "Perceiver", "data": { "range": 320, "fovDegrees": 360 } },+ { "type": "NavAgent", "data": { "speed": 125, "arriveRadius": 48, "repathInterval": 0.5 } },+ { "type": "BehaviorTreeAgent", "data": { "bt": "assets/ai/wisp.esbt" } },+ { "type": "RigidBody", "data": { "bodyType": 1 } },+ { "type": "CircleCollider", "data": { "radius": 0.26, "offset": { "x": 0, "y": -0.3 }, "categoryBits": 4, "maskBits": 1 } }+ ],+ "visible": true+ },+ {+ "id": 300,+ "name": "HealthBar_Back",+ "parent": 30,+ "children": [],+ "folder": "Actors",+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 66, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 76, "y": 12 }, "color": { "r": 0.078, "g": 0.067, "b": 0.125, "a": 1 }, "layer": 3 } }+ ],+ "visible": true+ },+ {+ "id": 301,+ "name": "HealthBar_Fill",+ "parent": 30,+ "children": [],+ "folder": "Actors",+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 66, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 72, "y": 8 }, "color": { "r": 0.906, "g": 0.353, "b": 0.412, "a": 1 }, "layer": 3 } },+ { "type": "HealthBarFill", "data": { "width": 72 } }+ ],+ "visible": true+ },+ {+ "id": 310,+ "name": "HealthBar_Back",+ "parent": 31,+ "children": [],+ "folder": "Actors",+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 66, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 76, "y": 12 }, "color": { "r": 0.078, "g": 0.067, "b": 0.125, "a": 1 }, "layer": 3 } }+ ],+ "visible": true+ },+ {+ "id": 311,+ "name": "HealthBar_Fill",+ "parent": 31,+ "children": [],+ "folder": "Actors",+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 66, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 72, "y": 8 }, "color": { "r": 0.906, "g": 0.353, "b": 0.412, "a": 1 }, "layer": 3 } },+ { "type": "HealthBarFill", "data": { "width": 72 } }],"visible": true}diff --git a/examples/celestial-heights/project.esproject b/examples/celestial-heights/project.esprojectindex 8981877b0..ccd5c2d85 100644--- a/examples/celestial-heights/project.esproject+++ b/examples/celestial-heights/project.esproject@@ -9,5 +9,16 @@"width": 1920,"height": 1080},- "spineVersion": "none"+ "spineVersion": "none",+ "features": {+ "physics": {+ "enabled": true,+ "gravity": { "x": 0, "y": 0 },+ "collisionLayers": ["World", "Player", "Enemy"]+ },+ "rendering": {+ "sortingLayers": ["Ground", "GroundDetail", "Actors", "Overhead", "Vfx"],+ "ySortLayers": [2]+ }+ }}diff --git a/examples/celestial-heights/src/ai/wisp.ts b/examples/celestial-heights/src/ai/wisp.tsnew file mode 100644index 000000000..36190fd8c--- /dev/null+++ b/examples/celestial-heights/src/ai/wisp.ts@@ -0,0 +1,65 @@+import {+ defineSystem, Query, Mut, Res,+ registerAction, registerCondition, setNavDestination,+ Nav, NavGrid, Perception, Status,+} from 'esengine';+import { Facing, MeleeAttack } from '../components';+import { ROOM_HALF_W, ROOM_HALF_H } from '../config';++// Leaves for assets/ai/wisp.esbt. The tree is authored as data and resolves+// these names from the engine's AI registry, so the brain's shape is editable+// without touching code and the code stays a vocabulary rather than a plan.++registerCondition('seesPlayer', (ctx) => ctx.has(Perception) && ctx.get(Perception).visible);++registerCondition('inStrikeRange', (ctx) => {+ if (!ctx.has(Perception) || !ctx.has(MeleeAttack)) return false;+ const perception = ctx.get(Perception);+ // Short of the full reach, so the wisp closes in rather than poking from the+ // edge of its own arc.+ return perception.visible && perception.distance <= ctx.get(MeleeAttack).reach * 0.75;+});++registerAction('strike', (ctx) => {+ if (!ctx.has(MeleeAttack)) return Status.Failure;+ ctx.set(MeleeAttack, { ...ctx.get(MeleeAttack), pending: true });+ return Status.Success;+});++registerAction('chase', (ctx) => {+ if (!ctx.has(Perception)) return Status.Failure;+ const perception = ctx.get(Perception);+ if (!perception.visible) return Status.Failure;+ setNavDestination(ctx.world, ctx.entity, { x: perception.targetX, y: perception.targetY });+ return Status.Running;+});++registerAction('hover', () => Status.Running);++/** Whoever can see turns to what they see, so their arc points at it. */+export const perceiverFacingSystem = defineSystem(+ [Query(Mut(Facing), Perception)],+ (perceivers) => {+ for (const [, facing, perception] of perceivers) {+ if (!perception.visible) continue;+ facing.x = perception.dirX;+ facing.y = perception.dirY;+ }+ },+ { name: 'PerceiverFacingSystem' },+);++/** An open grid over the room, until the room is a tilemap to derive one from. */+export const setupNavGridSystem = defineSystem(+ [Res(Nav)],+ (nav) => {+ const cell = 25;+ nav.setGrid(new NavGrid({+ width: (ROOM_HALF_W * 2) / cell,+ height: (ROOM_HALF_H * 2) / cell,+ cellSize: cell,+ origin: { x: -ROOM_HALF_W, y: -ROOM_HALF_H },+ }));+ },+ { name: 'SetupNavGridSystem' },+);diff --git a/examples/celestial-heights/src/components.ts b/examples/celestial-heights/src/components.tsindex 05f3316fe..a55ac9ef7 100644--- a/examples/celestial-heights/src/components.ts+++ b/examples/celestial-heights/src/components.ts@@ -1,4 +1,4 @@-import { defineComponent } from 'esengine';+import { defineComponent, defineTag } from 'esengine';// The project's declaration entry: user component/tag definitions only, no// systems. The editor extracts schemas from here so the inspector knows their@@ -8,3 +8,56 @@ import { defineComponent } from 'esengine';export const Player = defineComponent('Player', {speed: 380,});++/** Anything the player fights. */+export const Enemy = defineTag('Enemy');++/**+ * Where the actor is facing, as a unit vector. Melee arcs and animation both+ * read it, so it is written once per actor rather than derived twice from+ * whatever moved them.+ */+export const Facing = defineComponent('Facing', {+ x: 1,+ y: 0,+});++export const Health = defineComponent('Health', {+ current: 100,+ max: 100,+ /** Seconds of invulnerability a hit grants, so one swing lands once. */+ invulnerability: 0.35,+ /** Counts down; > 0 means further damage is ignored. */+ invulnerable: 0,+});++/**+ * The filled part of a floating health bar. It is a child of the actor it+ * reports on, so the bar follows without anyone having to copy a position.+ */+export const HealthBarFill = defineComponent('HealthBarFill', {+ /** Bar width at full health, in world units. */+ width: 72,+});++/**+ * One melee attack, for whoever swings it. Input and the wisps' behaviour tree+ * both only set `pending`, and one resolver turns that into an overlap query, an+ * arc test and damage — so `hits`, the mask of what a swing can reach, is the+ * only thing separating Lyra's sword from a wisp's touch.+ */+export const MeleeAttack = defineComponent('MeleeAttack', {+ damage: 25,+ /** Swing radius in world units. */+ reach: 96,+ /** Full width of the swing arc, centred on `Facing`, in degrees. */+ arcDegrees: 120,+ /** Seconds between swings. */+ cooldown: 0.45,+ /** Counts down; a swing is only allowed at 0. */+ cooldownLeft: 0,+ /** Set by whoever wants to swing; cleared by the resolver. */+ pending: false,+ /** Collision bits this attack can hit. */+ hits: 0,+});diff --git a/examples/celestial-heights/src/config.ts b/examples/celestial-heights/src/config.tsindex 4f45a407d..2bcd9341e 100644--- a/examples/celestial-heights/src/config.ts+++ b/examples/celestial-heights/src/config.ts@@ -1,10 +1,36 @@-/** Half-extents of the walkable ground, in world units. */-export const WALK_HALF_W = 860;-export const WALK_HALF_H = 420;+/**+ * Sorting layer indices — the order of `features.rendering.sortingLayers` in+ * project.esproject. `Actors` is the y-sorted one, which is what makes a 3/4+ * view read: who is nearer the camera is decided by world Y, not by spawn order.+ */+export const SortingLayer = {+ Ground: 0,+ GroundDetail: 1,+ Actors: 2,+ Overhead: 3,+ Vfx: 4,+} as const;++/** Collision filter bits — `features.physics.collisionLayers`, as masks. */+export const Collide = {+ World: 1 << 0,+ Player: 1 << 1,+ Enemy: 1 << 2,+} as const;++/** Half-extents of the walkable room, in world units. */+export const ROOM_HALF_W = 800;+export const ROOM_HALF_H = 450;/**- * A 3/4 top-down view foreshortens depth, so a step "north" covers less ground- * than a step "east". Vertical input is scaled by this to keep the two reading- * as the same speed.+ * A 3/4 view foreshortens depth, so a step "north" covers less ground than a+ * step "east". Vertical input is scaled by this so the two read as one speed.*/export const DEPTH_FORESHORTEN = 0.6;++/**+ * Inside this radius an attack ignores its own arc. Something standing on top+ * of you has no direction to be in front of: the offset is a couple of units of+ * noise, so a facing cone rejects or accepts it at random.+ */+export const POINT_BLANK = 40;diff --git a/examples/celestial-heights/src/events.ts b/examples/celestial-heights/src/events.tsnew file mode 100644index 000000000..c9678948d--- /dev/null+++ b/examples/celestial-heights/src/events.ts@@ -0,0 +1,15 @@+import { defineEvent, type Entity } from 'esengine';++/**+ * Everything that hurts anything goes through here, so invulnerability frames,+ * death and (later) hit reactions exist once instead of once per attacker.+ */+export const DamageDealt = defineEvent<{+ target: Entity;+ amount: number;+ /** Where the blow came from, for knockback and hit sparks. */+ fromX: number;+ fromY: number;+}>('DamageDealt');++export const Died = defineEvent<{ entity: Entity; isPlayer: boolean }>('Died');diff --git a/examples/celestial-heights/src/main.ts b/examples/celestial-heights/src/main.tsindex 7b4fddcfe..19b8a590d 100644--- a/examples/celestial-heights/src/main.ts+++ b/examples/celestial-heights/src/main.ts@@ -1,6 +1,25 @@-import { addSystemToSchedule, Schedule } from 'esengine';+import { addStartupSystem, addSystemToSchedule, Schedule } from 'esengine';import './components';-import { playerMoveSystem } from './systems/player';+import { playerMoveSystem, playerAttackSystem } from './systems/player';+import {+ meleeResolveSystem, damageSystem, invulnerabilitySystem, deathSystem,+} from './systems/combat';+import { healthBarSystem, hitFlashSystem } from './systems/feedback';+import { perceiverFacingSystem, setupNavGridSystem } from './ai/wisp';++// Perception, nav following and the behaviour-tree tick are engine plugins and+// need no wiring; only the project's own systems are registered here.+addStartupSystem(setupNavGridSystem);addSystemToSchedule(Schedule.Update, playerMoveSystem);+addSystemToSchedule(Schedule.Update, playerAttackSystem);+addSystemToSchedule(Schedule.Update, perceiverFacingSystem);+// Damage resolves after everyone has decided to swing, and death after damage,+// so a hit lands in the frame it was thrown rather than the next one.+addSystemToSchedule(Schedule.PostUpdate, meleeResolveSystem);+addSystemToSchedule(Schedule.PostUpdate, damageSystem);+addSystemToSchedule(Schedule.PostUpdate, deathSystem);+addSystemToSchedule(Schedule.PostUpdate, invulnerabilitySystem);+addSystemToSchedule(Schedule.PostUpdate, healthBarSystem);+addSystemToSchedule(Schedule.PostUpdate, hitFlashSystem);diff --git a/examples/celestial-heights/src/systems/combat.ts b/examples/celestial-heights/src/systems/combat.tsnew file mode 100644index 000000000..c06691fb7--- /dev/null+++ b/examples/celestial-heights/src/systems/combat.ts@@ -0,0 +1,83 @@+import {+ defineSystem, Query, Mut, Res, Time, Transform, Physics, Commands,+ EventWriter, EventReader, GetWorld,+} from 'esengine';+import { Facing, Health, MeleeAttack, Player } from '../components';+import { DamageDealt, Died } from '../events';+import { POINT_BLANK } from '../config';++const DEG = Math.PI / 180;++/**+ * The one place a swing becomes damage, for the player and for every enemy. The+ * overlap query is the physics world's; `hits` decides who a swing can reach,+ * which is the only difference between Lyra's sword and a wisp's touch.+ */+export const meleeResolveSystem = defineSystem(+ [+ Query(Transform, Facing, Mut(MeleeAttack)),+ Res(Time), Res(Physics), GetWorld(), EventWriter(DamageDealt),+ ],+ (attackers, time, physics, world, damage) => {+ for (const [attacker, transform, facing, attack] of attackers) {+ if (attack.cooldownLeft > 0) attack.cooldownLeft -= time.delta;+ if (!attack.pending) continue;+ attack.pending = false;+ if (attack.cooldownLeft > 0) continue;+ attack.cooldownLeft = attack.cooldown;++ const origin = transform.position;+ const minDot = Math.cos((attack.arcDegrees / 2) * DEG);+ for (const target of physics.overlapCircle(origin, attack.reach, attack.hits)) {+ if (target === attacker || !world.has(target, Transform)) continue;+ const p = world.get(target, Transform).position;+ const dx = p.x - origin.x;+ const dy = p.y - origin.y;+ const dist = Math.hypot(dx, dy);+ if (dist > POINT_BLANK && (dx * facing.x + dy * facing.y) / dist < minDot) continue;+ damage.send({ target, amount: attack.damage, fromX: origin.x, fromY: origin.y });+ }+ }+ },+ { name: 'MeleeResolveSystem' },+);++/** Applies damage, honours invulnerability frames, and announces deaths. */+export const damageSystem = defineSystem(+ [EventReader(DamageDealt), GetWorld(), EventWriter(Died)],+ (blows, world, died) => {+ for (const blow of blows) {+ if (!world.has(blow.target, Health)) continue;+ const health = world.get(blow.target, Health);+ if (health.invulnerable > 0 || health.current <= 0) continue;+ health.current -= blow.amount;+ health.invulnerable = health.invulnerability;+ if (health.current <= 0) {+ health.current = 0;+ died.send({ entity: blow.target, isPlayer: world.has(blow.target, Player) });+ }+ }+ },+ { name: 'DamageSystem' },+);++export const invulnerabilitySystem = defineSystem(+ [Query(Mut(Health)), Res(Time)],+ (bodies, time) => {+ for (const [, health] of bodies) {+ if (health.invulnerable > 0) health.invulnerable -= time.delta;+ }+ },+ { name: 'InvulnerabilitySystem' },+);++/** Enemies leave the world; Lyra's death is the game's business, not a despawn. */+export const deathSystem = defineSystem(+ [EventReader(Died), Commands()],+ (deaths, commands) => {+ for (const death of deaths) {+ if (!death.isPlayer) commands.despawn(death.entity);+ }+ },+ { name: 'DeathSystem' },+);diff --git a/examples/celestial-heights/src/systems/feedback.ts b/examples/celestial-heights/src/systems/feedback.tsnew file mode 100644index 000000000..1cf8ce329--- /dev/null+++ b/examples/celestial-heights/src/systems/feedback.ts@@ -0,0 +1,37 @@+import {+ defineSystem, Query, Mut, Transform, Sprite, Parent, GetWorld,+} from 'esengine';+import { Health, HealthBarFill } from '../components';++/**+ * Shrinks a bar towards its left edge. Scaling would take it in from both+ * sides, which reads as the bar moving rather than draining, so the width is+ * set and the position walks half the difference back.+ */+export const healthBarSystem = defineSystem(+ [Query(Mut(Transform), Mut(Sprite), HealthBarFill, Parent), GetWorld()],+ (bars, world) => {+ for (const [, transform, sprite, bar, parent] of bars) {+ if (!world.has(parent.entity, Health)) continue;+ const health = world.get(parent.entity, Health);+ const fraction = health.max > 0 ? Math.max(0, health.current / health.max) : 0;+ const width = bar.width * fraction;+ sprite.size.x = width;+ transform.position.x = -(bar.width - width) / 2;+ }+ },+ { name: 'HealthBarSystem' },+);++/** Blinks whoever is in invulnerability frames, so a hit is visible at all. */+export const hitFlashSystem = defineSystem(+ [Query(Mut(Sprite), Health)],+ (bodies) => {+ for (const [, sprite, health] of bodies) {+ sprite.color.a = health.invulnerable > 0+ ? (Math.floor(health.invulnerable * 12) % 2 === 0 ? 0.3 : 1)+ : 1;+ }+ },+ { name: 'HitFlashSystem' },+);diff --git a/examples/celestial-heights/src/systems/player.ts b/examples/celestial-heights/src/systems/player.tsindex 8cccd6325..4943532b0 100644--- a/examples/celestial-heights/src/systems/player.ts+++ b/examples/celestial-heights/src/systems/player.ts@@ -1,27 +1,48 @@-import { defineSystem, Query, Mut, Res, Time, Input, Transform } from 'esengine';-import { Player } from '../components';-import { WALK_HALF_W, WALK_HALF_H, DEPTH_FORESHORTEN } from '../config';--const clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);+import {+ defineSystem, Query, Mut, Res, Input, CharacterController,+} from 'esengine';+import { Player, Facing, MeleeAttack } from '../components';+import { DEPTH_FORESHORTEN } from '../config';+/**+ * Writes the desired velocity and lets the engine's character controller do the+ * moving — it collides the capsule and resolves the slide, so walls are the+ * physics world's business and not this system's.+ */export const playerMoveSystem = defineSystem(- [Query(Mut(Transform), Player), Res(Input), Res(Time)],- (query, input, time) => {- for (const [, transform, player] of query) {+ [Query(Mut(CharacterController), Mut(Facing), Player), Res(Input)],+ (players, input) => {+ for (const [, cc, facing, player] of players) {let dx = 0;let dy = 0;if (input.isKeyDown('KeyW') || input.isKeyDown('ArrowUp')) dy += 1;if (input.isKeyDown('KeyS') || input.isKeyDown('ArrowDown')) dy -= 1;if (input.isKeyDown('KeyA') || input.isKeyDown('ArrowLeft')) dx -= 1;if (input.isKeyDown('KeyD') || input.isKeyDown('ArrowRight')) dx += 1;- if (dx === 0 && dy === 0) continue;- const len = Math.sqrt(dx * dx + dy * dy);- const step = (player.speed * time.delta) / len;- const p = transform.position;- p.x = clamp(p.x + dx * step, -WALK_HALF_W, WALK_HALF_W);- p.y = clamp(p.y + dy * step * DEPTH_FORESHORTEN, -WALK_HALF_H, WALK_HALF_H);+ if (dx === 0 && dy === 0) {+ cc.velocity.x = 0;+ cc.velocity.y = 0;+ continue;+ }+ const len = Math.hypot(dx, dy);+ cc.velocity.x = (dx / len) * player.speed;+ cc.velocity.y = (dy / len) * player.speed * DEPTH_FORESHORTEN;+ // Facing follows input rather than resolved motion, so sliding along+ // a wall does not turn Lyra to face it.+ facing.x = dx / len;+ facing.y = dy / len;}},{ name: 'PlayerMoveSystem' },);++/** Turns the attack key into the same `pending` flag the wisps' brain sets. */+export const playerAttackSystem = defineSystem(+ [Query(Mut(MeleeAttack), Player), Res(Input)],+ (players, input) => {+ if (!input.isKeyPressed('Space')) return;+ for (const [, attack] of players) attack.pending = true;+ },+ { name: 'PlayerAttackSystem' },+);