Skip to content

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.

feat(gameplay): a swing, and the three facts it is made of

esengineb231bb8ca08b
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 07fb4b239..d9e5f2b17 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 84 beta · 1581 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1596 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -23,6 +23,11 @@ readonly AnchorAxis[]
readonly ["local", "subpackage", "remote"]
```
+## ATTACK_KEY — const @experimental
+```
+"KeyJ"
+```
+
## AchievementProvider — interface @experimental
```
getStat: (name: string) => number
@@ -1628,6 +1633,21 @@ CollisionBrush[]
"builtin:collision"
```
+## COMBAT_ATTACK_END — const @experimental
+```
+"attack-end"
+```
+
+## COMBAT_ATTACK_START — const @experimental
+```
+"attack-start"
+```
+
+## COMBAT_HIT — const @experimental
+```
+"hit"
+```
+
## CacheAsBitmap — const @experimental
```
ComponentDef<CacheAsBitmapData>
@@ -2510,6 +2530,21 @@ ScreenScalingData
"unattributed"
```
+## Damage — const @experimental
+```
+EventDef<DamagePayload>
+```
+
+## DamagePayload — interface @experimental
+```
+amount: number
+source: number
+target: number
+x: number
+y: number
+z: number
+```
+
## DataSource — interface @experimental
```
getCount: () => number
@@ -3811,6 +3846,17 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## Health — const @experimental
+```
+ComponentDef<HealthData>
+```
+
+## HealthData — interface @experimental
+```
+current: number
+max: number
+```
+
## HingeJoint2D — const @experimental
```
ComponentDef<HingeJoint2DData>
@@ -4718,6 +4764,39 @@ static new (opts: MeasuredLinearLayoutOptions): MeasuredLinearLayoutProvider
static prototype: MeasuredLinearLayoutProvider
```
+## MeleeAttack — const @experimental
+```
+ComponentDef<MeleeAttackData>
+```
+
+## MeleeAttackData — interface @experimental
+```
+anchor: number
+attackId: number
+damage: number
+enabled: boolean
+hitCount: number
+layers: number
+radius: number
+```
+
+## MeleeAttacks — class @experimental
+```
+clear: () => void
+close: (entity: Entity) => void
+forget: (entity: Entity) => void
+live: (entity: Entity) => { id: number; hits: number; } | null
+open: (entity: Entity) => number
+record: (entity: Entity, target: Entity) => boolean
+static new (): MeleeAttacks
+static prototype: MeleeAttacks
+```
+
+## MeleeOverlapQuery — interface @experimental
+```
+overlapSphere: (centre: { x: number; y: number; z: number; }, radius: number, layerMask?: number) => readonly Overlap3DHit[]
+```
+
## MemoryTransport — class @experimental
```
delivery: "reliable-ordered"
@@ -8222,6 +8301,11 @@ number
"timeline"
```
+## TPC_ATTACK — const @experimental
+```
+"attack"
+```
+
## TPC_DODGE — const @experimental
```
"dodge"
@@ -10106,6 +10190,11 @@ AnimationPlugin
(app: { setMaxDeltaTime(v: number): void; setMaxFixedSteps(v: number): void; }, config: RuntimeBuildConfig): void
```
+## applyDamage — function @experimental
+```
+(world: World, blows: Iterable<DamagePayload>): void
+```
+
## applyDeltaToSource — function @experimental
```
(source: PrefabData, delta: SourceDelta): PrefabData
@@ -12336,6 +12425,11 @@ ReplicationPlugin
(world: Pick<World, "tryGet">, rootEntity: Entity, childPath: string): Entity | null
```
+## resolveMeleeHits — function @experimental
+```
+(world: World, attacks: MeleeAttacks, queries: MeleeOverlapQuery | null, events: Iterable<AnimatorEventPayload>, damage: { send(blow: DamagePayload): void; }): void
+```
+
## resolveParams — function @experimental
```
(def: AnimatorControllerDef, overrides: ReadonlyMap<string, number | boolean>): Record<string, number | boolean>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index c18cad771..7c3294e69 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 89 beta · 1600 experimental · 3 deprecated
+Symbols: 113 public · 89 beta · 1615 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -23,6 +23,11 @@ readonly AnchorAxis[]
readonly ["local", "subpackage", "remote"]
```
+## ATTACK_KEY — const @experimental
+```
+"KeyJ"
+```
+
## AchievementProvider — interface @experimental
```
getStat: (name: string) => number
@@ -1628,6 +1633,21 @@ CollisionBrush[]
"builtin:collision"
```
+## COMBAT_ATTACK_END — const @experimental
+```
+"attack-end"
+```
+
+## COMBAT_ATTACK_START — const @experimental
+```
+"attack-start"
+```
+
+## COMBAT_HIT — const @experimental
+```
+"hit"
+```
+
## CacheAsBitmap — const @experimental
```
ComponentDef<CacheAsBitmapData>
@@ -2518,6 +2538,21 @@ ScreenScalingData
"unattributed"
```
+## Damage — const @experimental
+```
+EventDef<DamagePayload>
+```
+
+## DamagePayload — interface @experimental
+```
+amount: number
+source: number
+target: number
+x: number
+y: number
+z: number
+```
+
## DataSource — interface @experimental
```
getCount: () => number
@@ -3819,6 +3854,17 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## Health — const @experimental
+```
+ComponentDef<HealthData>
+```
+
+## HealthData — interface @experimental
+```
+current: number
+max: number
+```
+
## HingeJoint2D — const @experimental
```
ComponentDef<HingeJoint2DData>
@@ -4726,6 +4772,39 @@ static new (opts: MeasuredLinearLayoutOptions): MeasuredLinearLayoutProvider
static prototype: MeasuredLinearLayoutProvider
```
+## MeleeAttack — const @experimental
+```
+ComponentDef<MeleeAttackData>
+```
+
+## MeleeAttackData — interface @experimental
+```
+anchor: number
+attackId: number
+damage: number
+enabled: boolean
+hitCount: number
+layers: number
+radius: number
+```
+
+## MeleeAttacks — class @experimental
+```
+clear: () => void
+close: (entity: Entity) => void
+forget: (entity: Entity) => void
+live: (entity: Entity) => { id: number; hits: number; } | null
+open: (entity: Entity) => number
+record: (entity: Entity, target: Entity) => boolean
+static new (): MeleeAttacks
+static prototype: MeleeAttacks
+```
+
+## MeleeOverlapQuery — interface @experimental
+```
+overlapSphere: (centre: { x: number; y: number; z: number; }, radius: number, layerMask?: number) => readonly Overlap3DHit[]
+```
+
## MemoryProvider — interface @experimental
```
resolveComponentHeap: (cppName: string) => ComponentHeapResolver | null
@@ -8415,6 +8494,11 @@ number
"timeline"
```
+## TPC_ATTACK — const @experimental
+```
+"attack"
+```
+
## TPC_DODGE — const @experimental
```
"dodge"
@@ -10299,6 +10383,11 @@ AnimationPlugin
(app: { setMaxDeltaTime(v: number): void; setMaxFixedSteps(v: number): void; }, config: RuntimeBuildConfig): void
```
+## applyDamage — function @experimental
+```
+(world: World, blows: Iterable<DamagePayload>): void
+```
+
## applyDeltaToSource — function @experimental
```
(source: PrefabData, delta: SourceDelta): PrefabData
@@ -12579,6 +12668,11 @@ ReplicationPlugin
(world: Pick<World, "tryGet">, rootEntity: Entity, childPath: string): Entity | null
```
+## resolveMeleeHits — function @experimental
+```
+(world: World, attacks: MeleeAttacks, queries: MeleeOverlapQuery | null, events: Iterable<AnimatorEventPayload>, damage: { send(blow: DamagePayload): void; }): void
+```
+
## resolveParams — function @experimental
```
(def: AnimatorControllerDef, overrides: ReadonlyMap<string, number | boolean>): Record<string, number | boolean>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index de586be8b..c2b8edc90 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 86 beta · 1580 experimental · 3 deprecated
+Symbols: 113 public · 86 beta · 1595 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -18,6 +18,11 @@ readonly AnchorAxis[]
readonly ["local", "subpackage", "remote"]
```
+## ATTACK_KEY — const @experimental
+```
+"KeyJ"
+```
+
## AchievementProvider — interface @experimental
```
getStat: (name: string) => number
@@ -1623,6 +1628,21 @@ CollisionBrush[]
"builtin:collision"
```
+## COMBAT_ATTACK_END — const @experimental
+```
+"attack-end"
+```
+
+## COMBAT_ATTACK_START — const @experimental
+```
+"attack-start"
+```
+
+## COMBAT_HIT — const @experimental
+```
+"hit"
+```
+
## CacheAsBitmap — const @experimental
```
ComponentDef<CacheAsBitmapData>
@@ -2505,6 +2525,21 @@ ScreenScalingData
"unattributed"
```
+## Damage — const @experimental
+```
+EventDef<DamagePayload>
+```
+
+## DamagePayload — interface @experimental
+```
+amount: number
+source: number
+target: number
+x: number
+y: number
+z: number
+```
+
## DataSource — interface @experimental
```
getCount: () => number
@@ -3806,6 +3841,17 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## Health — const @experimental
+```
+ComponentDef<HealthData>
+```
+
+## HealthData — interface @experimental
+```
+current: number
+max: number
+```
+
## HingeJoint2D — const @experimental
```
ComponentDef<HingeJoint2DData>
@@ -4713,6 +4759,39 @@ static new (opts: MeasuredLinearLayoutOptions): MeasuredLinearLayoutProvider
static prototype: MeasuredLinearLayoutProvider
```
+## MeleeAttack — const @experimental
+```
+ComponentDef<MeleeAttackData>
+```
+
+## MeleeAttackData — interface @experimental
+```
+anchor: number
+attackId: number
+damage: number
+enabled: boolean
+hitCount: number
+layers: number
+radius: number
+```
+
+## MeleeAttacks — class @experimental
+```
+clear: () => void
+close: (entity: Entity) => void
+forget: (entity: Entity) => void
+live: (entity: Entity) => { id: number; hits: number; } | null
+open: (entity: Entity) => number
+record: (entity: Entity, target: Entity) => boolean
+static new (): MeleeAttacks
+static prototype: MeleeAttacks
+```
+
+## MeleeOverlapQuery — interface @experimental
+```
+overlapSphere: (centre: { x: number; y: number; z: number; }, radius: number, layerMask?: number) => readonly Overlap3DHit[]
+```
+
## MemoryTransport — class @experimental
```
delivery: "reliable-ordered"
@@ -8217,6 +8296,11 @@ number
"timeline"
```
+## TPC_ATTACK — const @experimental
+```
+"attack"
+```
+
## TPC_DODGE — const @experimental
```
"dodge"
@@ -10101,6 +10185,11 @@ AnimationPlugin
(app: { setMaxDeltaTime(v: number): void; setMaxFixedSteps(v: number): void; }, config: RuntimeBuildConfig): void
```
+## applyDamage — function @experimental
+```
+(world: World, blows: Iterable<DamagePayload>): void
+```
+
## applyDeltaToSource — function @experimental
```
(source: PrefabData, delta: SourceDelta): PrefabData
@@ -12341,6 +12430,11 @@ ReplicationPlugin
(world: Pick<World, "tryGet">, rootEntity: Entity, childPath: string): Entity | null
```
+## resolveMeleeHits — function @experimental
+```
+(world: World, attacks: MeleeAttacks, queries: MeleeOverlapQuery | null, events: Iterable<AnimatorEventPayload>, damage: { send(blow: DamagePayload): void; }): void
+```
+
## resolveParams — function @experimental
```
(def: AnimatorControllerDef, overrides: ReadonlyMap<string, number | boolean>): Record<string, number | boolean>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 3e97bb7b0..434d6fa76 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 84 beta · 1602 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1617 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -18,6 +18,11 @@ readonly AnchorAxis[]
readonly ["local", "subpackage", "remote"]
```
+## ATTACK_KEY — const @experimental
+```
+"KeyJ"
+```
+
## AchievementProvider — interface @experimental
```
getStat: (name: string) => number
@@ -1623,6 +1628,21 @@ CollisionBrush[]
"builtin:collision"
```
+## COMBAT_ATTACK_END — const @experimental
+```
+"attack-end"
+```
+
+## COMBAT_ATTACK_START — const @experimental
+```
+"attack-start"
+```
+
+## COMBAT_HIT — const @experimental
+```
+"hit"
+```
+
## CacheAsBitmap — const @experimental
```
ComponentDef<CacheAsBitmapData>
@@ -2505,6 +2525,21 @@ ScreenScalingData
"unattributed"
```
+## Damage — const @experimental
+```
+EventDef<DamagePayload>
+```
+
+## DamagePayload — interface @experimental
+```
+amount: number
+source: number
+target: number
+x: number
+y: number
+z: number
+```
+
## DataSource — interface @experimental
```
getCount: () => number
@@ -3806,6 +3841,17 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## Health — const @experimental
+```
+ComponentDef<HealthData>
+```
+
+## HealthData — interface @experimental
+```
+current: number
+max: number
+```
+
## HingeJoint2D — const @experimental
```
ComponentDef<HingeJoint2DData>
@@ -4713,6 +4759,39 @@ static new (opts: MeasuredLinearLayoutOptions): MeasuredLinearLayoutProvider
static prototype: MeasuredLinearLayoutProvider
```
+## MeleeAttack — const @experimental
+```
+ComponentDef<MeleeAttackData>
+```
+
+## MeleeAttackData — interface @experimental
+```
+anchor: number
+attackId: number
+damage: number
+enabled: boolean
+hitCount: number
+layers: number
+radius: number
+```
+
+## MeleeAttacks — class @experimental
+```
+clear: () => void
+close: (entity: Entity) => void
+forget: (entity: Entity) => void
+live: (entity: Entity) => { id: number; hits: number; } | null
+open: (entity: Entity) => number
+record: (entity: Entity, target: Entity) => boolean
+static new (): MeleeAttacks
+static prototype: MeleeAttacks
+```
+
+## MeleeOverlapQuery — interface @experimental
+```
+overlapSphere: (centre: { x: number; y: number; z: number; }, radius: number, layerMask?: number) => readonly Overlap3DHit[]
+```
+
## MemoryTransport — class @experimental
```
delivery: "reliable-ordered"
@@ -8463,6 +8542,11 @@ number
"timeline"
```
+## TPC_ATTACK — const @experimental
+```
+"attack"
+```
+
## TPC_DODGE — const @experimental
```
"dodge"
@@ -10353,6 +10437,11 @@ AnimationPlugin
(app: { setMaxDeltaTime(v: number): void; setMaxFixedSteps(v: number): void; }, config: RuntimeBuildConfig): void
```
+## applyDamage — function @experimental
+```
+(world: World, blows: Iterable<DamagePayload>): void
+```
+
## applyDeltaToSource — function @experimental
```
(source: PrefabData, delta: SourceDelta): PrefabData
@@ -12598,6 +12687,11 @@ ReplicationPlugin
(world: Pick<World, "tryGet">, rootEntity: Entity, childPath: string): Entity | null
```
+## resolveMeleeHits — function @experimental
+```
+(world: World, attacks: MeleeAttacks, queries: MeleeOverlapQuery | null, events: Iterable<AnimatorEventPayload>, damage: { send(blow: DamagePayload): void; }): void
+```
+
## resolveParams — function @experimental
```
(def: AnimatorControllerDef, overrides: ReadonlyMap<string, number | boolean>): Record<string, number | boolean>
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 6c90b78dc..032af972c 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 84 beta · 1592 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1607 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -18,6 +18,11 @@ readonly AnchorAxis[]
readonly ["local", "subpackage", "remote"]
```
+## ATTACK_KEY — const @experimental
+```
+"KeyJ"
+```
+
## AchievementProvider — interface @experimental
```
getStat: (name: string) => number
@@ -1623,6 +1628,21 @@ CollisionBrush[]
"builtin:collision"
```
+## COMBAT_ATTACK_END — const @experimental
+```
+"attack-end"
+```
+
+## COMBAT_ATTACK_START — const @experimental
+```
+"attack-start"
+```
+
+## COMBAT_HIT — const @experimental
+```
+"hit"
+```
+
## CacheAsBitmap — const @experimental
```
ComponentDef<CacheAsBitmapData>
@@ -2505,6 +2525,21 @@ ScreenScalingData
"unattributed"
```
+## Damage — const @experimental
+```
+EventDef<DamagePayload>
+```
+
+## DamagePayload — interface @experimental
+```
+amount: number
+source: number
+target: number
+x: number
+y: number
+z: number
+```
+
## DataSource — interface @experimental
```
getCount: () => number
@@ -3806,6 +3841,17 @@ plugins: Plugin[] | undefined
sideModules: SideModuleHost | undefined
```
+## Health — const @experimental
+```
+ComponentDef<HealthData>
+```
+
+## HealthData — interface @experimental
+```
+current: number
+max: number
+```
+
## HingeJoint2D — const @experimental
```
ComponentDef<HingeJoint2DData>
@@ -4720,6 +4766,39 @@ static new (opts: MeasuredLinearLayoutOptions): MeasuredLinearLayoutProvider
static prototype: MeasuredLinearLayoutProvider
```
+## MeleeAttack — const @experimental
+```
+ComponentDef<MeleeAttackData>
+```
+
+## MeleeAttackData — interface @experimental
+```
+anchor: number
+attackId: number
+damage: number
+enabled: boolean
+hitCount: number
+layers: number
+radius: number
+```
+
+## MeleeAttacks — class @experimental
+```
+clear: () => void
+close: (entity: Entity) => void
+forget: (entity: Entity) => void
+live: (entity: Entity) => { id: number; hits: number; } | null
+open: (entity: Entity) => number
+record: (entity: Entity, target: Entity) => boolean
+static new (): MeleeAttacks
+static prototype: MeleeAttacks
+```
+
+## MeleeOverlapQuery — interface @experimental
+```
+overlapSphere: (centre: { x: number; y: number; z: number; }, radius: number, layerMask?: number) => readonly Overlap3DHit[]
+```
+
## MemoryTransport — class @experimental
```
delivery: "reliable-ordered"
@@ -8224,6 +8303,11 @@ number
"timeline"
```
+## TPC_ATTACK — const @experimental
+```
+"attack"
+```
+
## TPC_DODGE — const @experimental
```
"dodge"
@@ -10129,6 +10213,11 @@ AnimationPlugin
(app: { setMaxDeltaTime(v: number): void; setMaxFixedSteps(v: number): void; }, config: RuntimeBuildConfig): void
```
+## applyDamage — function @experimental
+```
+(world: World, blows: Iterable<DamagePayload>): void
+```
+
## applyDeltaToSource — function @experimental
```
(source: PrefabData, delta: SourceDelta): PrefabData
@@ -12364,6 +12453,11 @@ ReplicationPlugin
(world: Pick<World, "tryGet">, rootEntity: Entity, childPath: string): Entity | null
```
+## resolveMeleeHits — function @experimental
+```
+(world: World, attacks: MeleeAttacks, queries: MeleeOverlapQuery | null, events: Iterable<AnimatorEventPayload>, damage: { send(blow: DamagePayload): void; }): void
+```
+
## resolveParams — function @experimental
```
(def: AnimatorControllerDef, overrides: ReadonlyMap<string, number | boolean>): Record<string, number | boolean>
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 46d7e06ec..ae78f17e5 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -878,6 +878,7 @@ export {
TPC_SPEED,
TPC_GROUNDED,
TPC_DODGE,
+ TPC_ATTACK,
desiredDirection,
approachVelocity,
facingYaw,
@@ -892,6 +893,20 @@ export {
rootMotionVelocity,
WORLD_BASIS,
DODGE_KEY,
+ ATTACK_KEY,
+ Health,
+ Damage,
+ applyDamage,
+ MeleeAttack,
+ MeleeAttacks,
+ resolveMeleeHits,
+ COMBAT_ATTACK_START,
+ COMBAT_HIT,
+ COMBAT_ATTACK_END,
+ type HealthData,
+ type DamagePayload,
+ type MeleeAttackData,
+ type MeleeOverlapQuery,
type ThirdPersonControllerData,
type ThirdPersonCameraData,
type MoveBasis,
diff --git a/sdk/src/gameplay/GameplayPlugin.ts b/sdk/src/gameplay/GameplayPlugin.ts
index 38bc144de..64d5080a3 100644
--- a/sdk/src/gameplay/GameplayPlugin.ts
+++ b/sdk/src/gameplay/GameplayPlugin.ts
@@ -24,13 +24,17 @@ import { Animator, AnimatorController, type AnimatorControllerAPI } from '../ani
import {
AnimatorRootMotion, type AnimatorRootMotionData,
} from '../animation/animatorRootMotion';
+import { AnimatorEvent, type AnimatorEventPayload } from '../animation/animatorEvent';
+import { EventReader, EventWriter, type EventWriterInstance } from '../ecs/event';
+import { Damage, applyDamage, type DamagePayload } from './Health';
+import { MeleeAttacks, resolveMeleeHits } from './MeleeAttack';
import { q } from '../math/quat';
import type { World } from '../ecs/world';
import type { Entity } from '../types';
import {
ThirdPersonController, type ThirdPersonControllerData,
desiredDirection, approachVelocity, facingYaw, turnToward, rootMotionVelocity,
- yawQuaternion, yawOfQuaternion, WORLD_BASIS, DODGE_KEY, type MoveBasis,
+ yawQuaternion, yawOfQuaternion, WORLD_BASIS, DODGE_KEY, ATTACK_KEY, type MoveBasis,
} from './ThirdPersonController';
import {
ThirdPersonCamera, type ThirdPersonCameraData,
@@ -42,6 +46,8 @@ export const TPC_SPEED = 'speed';
export const TPC_GROUNDED = 'grounded';
/** The trigger a dodge press sets. Whether any state answers it is the graph's. */
export const TPC_DODGE = 'dodge';
+/** The trigger an attack press sets. The graph decides which state answers it. */
+export const TPC_ATTACK = 'attack';
/**
* What the animation is asking this character to do, or null when nothing is.
@@ -85,8 +91,11 @@ export function requestMotion(
const data = world.get(entity, ThirdPersonController) as ThirdPersonControllerData;
if (!data.enabled) continue;
- if (animator && world.has(entity, Animator) && input.isKeyPressed(DODGE_KEY)) {
- animator.setTrigger(entity, TPC_DODGE);
+ if (animator && world.has(entity, Animator)) {
+ // A press asks for the ACTION; which clip that is, and whether this
+ // character has one at all, stays the animator graph's answer.
+ if (input.isKeyPressed(DODGE_KEY)) animator.setTrigger(entity, TPC_DODGE);
+ if (input.isKeyPressed(ATTACK_KEY)) animator.setTrigger(entity, TPC_ATTACK);
}
const character = world.get(entity, CharacterController3D) as CharacterController3DData;
@@ -257,10 +266,39 @@ export function updateCameras(
export class GameplayPlugin implements Plugin {
name = 'gameplay';
private offDespawn_: (() => void) | null = null;
+ /** Per App, not per module: two Apps in one process must not share swings. */
+ private readonly attacks_ = new MeleeAttacks();
build(app: App): void {
const world = app.world;
- this.offDespawn_ = world.onDespawn((entity: Entity) => { lastPointer.delete(entity); });
+ const attacks = this.attacks_;
+ this.offDespawn_ = world.onDespawn((entity: Entity) => {
+ lastPointer.delete(entity);
+ attacks.forget(entity);
+ });
+
+ // BEFORE this frame's animator: the events are last frame's, and the
+ // joints still hold the pose that posted them. Running after would ask
+ // the query about a swing that has already moved on.
+ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
+ [EventReader(AnimatorEvent), EventWriter(Damage)],
+ (
+ events: Iterable<AnimatorEventPayload>,
+ damage: EventWriterInstance<DamagePayload>,
+ ) => {
+ const queries = app.hasResource(Physics3D) ? app.getResource(Physics3D) : null;
+ resolveMeleeHits(world, attacks, queries, events, damage);
+ },
+ { name: 'MeleeAttackSystem' },
+ ), { runIf: playModeOnly });
+
+ // The only writer of Health, and it reads a request rather than being
+ // called by whatever swung.
+ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
+ [EventReader(Damage)],
+ (blows: Iterable<DamagePayload>) => { applyDamage(world, blows); },
+ { name: 'DamageSystem' },
+ ), { runIf: playModeOnly });
// Before the physics step: what the player is asking for.
app.addSystemToSchedule(Schedule.FixedPreUpdate, defineSystem(
@@ -299,6 +337,7 @@ export class GameplayPlugin implements Plugin {
this.offDespawn_?.();
this.offDespawn_ = null;
lastPointer.clear();
+ this.attacks_.clear();
}
}
diff --git a/sdk/src/gameplay/Health.ts b/sdk/src/gameplay/Health.ts
new file mode 100644
index 000000000..cb7ab52d8
--- /dev/null
+++ b/sdk/src/gameplay/Health.ts
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Health.ts
+ * @brief What a blow is, and the one place it lands.
+ *
+ * @details A blow travels as a REQUEST on the {@link Damage} bus and one system
+ * answers it. Nothing else writes `Health` — not the thing that swung,
+ * not the physics query that found a body — so "how much is left" has a
+ * single author, and every rule that will ever sit between a hit and a
+ * health bar (armour, invulnerability, a shield) has one seam to sit in
+ * rather than an inlined subtraction to be found and edited.
+ *
+ * The bus is double buffered, so a blow sent this frame lands on the
+ * next. That is one frame between the animation's hit moment and the
+ * number changing, and it buys a combat system that never reaches into
+ * the thing it hit.
+ */
+
+import { defineComponent, type ComponentDef } from '../ecs/component';
+import { defineEvent, type EventDef } from '../ecs/event';
+import type { World } from '../ecs/world';
+import type { Entity } from '../types';
+
+/** The fields of the `Health` component. @experimental */
+export interface HealthData {
+ current: number;
+ max: number;
+}
+
+/**
+ * What something has left. Presence is also what makes an entity DAMAGEABLE: a
+ * combat query finds colliders, and the floor is one of them.
+ *
+ * @experimental
+ */
+export const Health: ComponentDef<HealthData> = defineComponent<HealthData>('Health', {
+ current: 100,
+ max: 100,
+}, {
+ fields: {
+ current: { min: 0 },
+ max: { min: 0 },
+ },
+});
+
+/**
+ * One blow, on its way to whoever it lands on.
+ *
+ * The point it landed at travels with it because presentation needs it and
+ * cannot recover it: by the time a spark is drawn, the swing has moved on.
+ *
+ * @experimental
+ */
+export interface DamagePayload {
+ target: Entity;
+ /** Who dealt it, so a blow cannot be traced back to nobody. */
+ source: Entity;
+ amount: number;
+ x: number;
+ y: number;
+ z: number;
+}
+
+/**
+ * The bus every blow travels on. Send it to deal damage; read it to answer one
+ * (a spark, a sound, a hit reaction).
+ *
+ * @experimental
+ */
+export const Damage: EventDef<DamagePayload> = defineEvent<DamagePayload>('Damage', {
+ target: 0 as Entity, source: 0 as Entity, amount: 0, x: 0, y: 0, z: 0,
+});
+
+/**
+ * Land every blow in `blows`. The ONLY writer of `Health` — a blow aimed at
+ * something that has none, or at something already down, is simply not applied.
+ */
+export function applyDamage(world: World, blows: Iterable<DamagePayload>): void {
+ for (const blow of blows) {
+ if (!world.valid(blow.target) || !world.has(blow.target, Health)) continue;
+ const health = world.get(blow.target, Health) as HealthData;
+ if (health.current <= 0) continue;
+ world.update(blow.target, Health, (h: HealthData) => {
+ h.current = Math.max(0, h.current - blow.amount);
+ });
+ }
+}
diff --git a/sdk/src/gameplay/MeleeAttack.ts b/sdk/src/gameplay/MeleeAttack.ts
new file mode 100644
index 000000000..bb81f9306
--- /dev/null
+++ b/sdk/src/gameplay/MeleeAttack.ts
@@ -0,0 +1,229 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file MeleeAttack.ts
+ * @brief The swing: when the animation says it connects, what was in the way,
+ * and who is allowed to be hurt by it.
+ *
+ * @details Three facts, kept apart on purpose:
+ *
+ * an animation event ≠ a hit ≠ damage
+ *
+ * The clip says only that the swing reached its effective moment. What
+ * is in that space is the physics world's answer, and what that does to
+ * anyone is gameplay's. Collapsing any two of them is what makes a
+ * combat system that cannot be re-aimed, re-timed or re-balanced.
+ *
+ * So: the animator posts `hit` and knows nothing about damage; the
+ * query is asked at the ANIMATED anchor and knows nothing about health;
+ * the filtering (self, already-hit, damageable) lives here and nowhere
+ * in the physics layer.
+ */
+
+import { defineComponent, type ComponentDef } from '../ecs/component';
+import { Transform, type TransformData } from '../ecs/component';
+import type { World } from '../ecs/world';
+import type { Entity } from '../types';
+import type { Overlap3DHit } from '../physics3d/Physics3DQueries';
+import type { AnimatorEventPayload } from '../animation/animatorEvent';
+import { Health, type DamagePayload } from './Health';
+
+/**
+ * The events a clip declares that this reads. Names rather than times: a state
+ * that re-times its swing re-times the hit, and nothing else has to be told.
+ */
+export const COMBAT_ATTACK_START = 'attack-start';
+export const COMBAT_HIT = 'hit';
+export const COMBAT_ATTACK_END = 'attack-end';
+
+/** The fields of the `MeleeAttack` component. @experimental */
+export interface MeleeAttackData {
+ /** Radius of the sphere a `hit` tests, in world units. */
+ radius: number;
+ /** What a landed blow takes off. */
+ damage: number;
+ /** Physics layers the swing can reach; 0 is every layer. */
+ layers: number;
+ /**
+ * The entity whose WORLD placement the query is centred on — a socket under
+ * an animated joint, so where the swing reaches is what the animation did.
+ * 0 falls back to the attacker itself, which is a body slam, not a sword.
+ */
+ anchor: Entity;
+ enabled: boolean;
+ /** Engine-written: the live swing, or 0 when none is running. */
+ attackId: number;
+ /** Engine-written: how many targets the live swing has landed on. */
+ hitCount: number;
+}
+
+/**
+ * A melee swing whose timing is the animation's and whose reach is the physics
+ * world's. Add it beside an `Animator` whose attack clip declares `attack-start`,
+ * `hit` and `attack-end`.
+ *
+ * @experimental
+ */
+export const MeleeAttack: ComponentDef<MeleeAttackData> =
+ defineComponent<MeleeAttackData>('MeleeAttack', {
+ radius: 60,
+ damage: 25,
+ layers: 0,
+ anchor: 0 as Entity,
+ enabled: true,
+ attackId: 0,
+ hitCount: 0,
+ }, {
+ entityFields: ['anchor'],
+ readonlyFields: ['attackId', 'hitCount'],
+ fields: {
+ radius: { min: 0 },
+ damage: { min: 0 },
+ layers: { min: 0, max: 15, step: 1, advanced: true },
+ anchor: { tooltip: 'The animated socket the swing reaches from.' },
+ attackId: { advanced: true },
+ hitCount: { advanced: true },
+ },
+ });
+
+// =============================================================================
+// Attack instances — what makes one swing land once
+// =============================================================================
+
+interface LiveAttack {
+ id: number;
+ /** Everything this swing has already landed on. */
+ hit: Set<Entity>;
+}
+
+/**
+ * The swings currently in the air, one per attacker: ONE swing lands on a target
+ * once, and the next one may land again. Leaning on "the event only fires once"
+ * is a contract the first multi-frame hit window breaks, and breaks silently —
+ * double damage reads as a balance problem, not a bug.
+ */
+export class MeleeAttacks {
+ private readonly live_ = new Map<Entity, LiveAttack>();
+ private nextId_ = 1;
+
+ /** Begin a swing, ending whatever this attacker had in the air. */
+ open(entity: Entity): number {
+ const id = this.nextId_++;
+ this.live_.set(entity, { id, hit: new Set() });
+ return id;
+ }
+
+ close(entity: Entity): void {
+ this.live_.delete(entity);
+ }
+
+ live(entity: Entity): { id: number; hits: number } | null {
+ const attack = this.live_.get(entity);
+ return attack ? { id: attack.id, hits: attack.hit.size } : null;
+ }
+
+ /**
+ * Record `target` as hit by this attacker's live swing. False when the swing
+ * already reached it, which is the whole point.
+ */
+ record(entity: Entity, target: Entity): boolean {
+ const attack = this.live_.get(entity);
+ if (!attack || attack.hit.has(target)) return false;
+ attack.hit.add(target);
+ return true;
+ }
+
+ /** Drop an attacker's swing (wire to world.onDespawn). */
+ forget(entity: Entity): void {
+ this.live_.delete(entity);
+ }
+
+ clear(): void {
+ this.live_.clear();
+ }
+}
+
+// =============================================================================
+// Resolution
+// =============================================================================
+
+/**
+ * The only thing a swing asks the physics world. Narrow on purpose: what is in
+ * this space is all physics can answer, and `Physics3DQueries` satisfies it
+ * without combat depending on the rest of that surface.
+ */
+export interface MeleeOverlapQuery {
+ overlapSphere(
+ centre: { x: number; y: number; z: number }, radius: number, layerMask?: number,
+ ): readonly Overlap3DHit[];
+}
+
+/** Where a swing reaches from: the animated anchor, else the attacker itself. */
+function anchorOf(world: World, attacker: Entity, attack: MeleeAttackData): Entity {
+ const anchor = attack.anchor;
+ return anchor && world.valid(anchor) && world.has(anchor, Transform) ? anchor : attacker;
+}
+
+/** Publish what the live swing is, for an inspector and for a driver to read. */
+function publish(world: World, entity: Entity, attacks: MeleeAttacks): void {
+ const live = attacks.live(entity);
+ world.update(entity, MeleeAttack, (data: MeleeAttackData) => {
+ data.attackId = live?.id ?? 0;
+ data.hitCount = live?.hits ?? 0;
+ });
+}
+
+/**
+ * Turn the animation events an attacker posted into blows.
+ *
+ * Runs on LAST frame's events, before this frame's animator poses anything:
+ * the joints still hold the pose that produced the event, so the swing is asked
+ * about the space it was actually in.
+ */
+export function resolveMeleeHits(
+ world: World, attacks: MeleeAttacks, queries: MeleeOverlapQuery | null,
+ events: Iterable<AnimatorEventPayload>,
+ damage: { send(blow: DamagePayload): void },
+): void {
+ for (const event of events) {
+ const attacker = event.entity;
+ if (!world.valid(attacker) || !world.has(attacker, MeleeAttack)) continue;
+ const attack = world.get(attacker, MeleeAttack) as MeleeAttackData;
+ if (!attack.enabled) continue;
+
+ if (event.name === COMBAT_ATTACK_START) {
+ attacks.open(attacker);
+ publish(world, attacker, attacks);
+ continue;
+ }
+ if (event.name === COMBAT_ATTACK_END) {
+ attacks.close(attacker);
+ publish(world, attacker, attacks);
+ continue;
+ }
+ if (event.name !== COMBAT_HIT) continue;
+
+ // A clip that says only `hit` still gets an instance, so its dedup holds;
+ // the ceremony is for clips with a window, not a requirement.
+ if (!attacks.live(attacker)) attacks.open(attacker);
+
+ const anchor = anchorOf(world, attacker, attack);
+ // The anchor hangs off an animated joint, so its world placement is
+ // composed rather than stored. O(1) when nothing moved.
+ world.ensureTransformsComposed();
+ const placement = world.get(anchor, Transform) as TransformData;
+ const centre = placement.worldPosition ?? placement.position;
+
+ for (const found of queries?.overlapSphere(centre, attack.radius, attack.layers) ?? []) {
+ // Gameplay's rules, none of them the physics world's to know.
+ if (found.entity === attacker) continue;
+ if (!world.valid(found.entity) || !world.has(found.entity, Health)) continue;
+ if (!attacks.record(attacker, found.entity)) continue;
+ damage.send({
+ target: found.entity, source: attacker, amount: attack.damage,
+ x: found.x, y: found.y, z: found.z,
+ });
+ }
+ publish(world, attacker, attacks);
+ }
+}
diff --git a/sdk/src/gameplay/ThirdPersonController.ts b/sdk/src/gameplay/ThirdPersonController.ts
index e8a276d38..4270fc858 100644
--- a/sdk/src/gameplay/ThirdPersonController.ts
+++ b/sdk/src/gameplay/ThirdPersonController.ts
@@ -23,6 +23,9 @@ import type { Vec3 } from '../types';
/** The key a dodge is asked for on; the animator decides whether there is one. */
export const DODGE_KEY = 'ShiftLeft';
+/** The key an attack is asked for on. Same rule: a request, not a clip name. */
+export const ATTACK_KEY = 'KeyJ';
+
/** The fields of the `ThirdPersonController` component. @experimental */
export interface ThirdPersonControllerData {
/** Top speed on the ground, world units per second. */
diff --git a/sdk/src/gameplay/index.ts b/sdk/src/gameplay/index.ts
index 663cb3fd3..d5a99a0af 100644
--- a/sdk/src/gameplay/index.ts
+++ b/sdk/src/gameplay/index.ts
@@ -12,6 +12,7 @@ export {
yawOfQuaternion,
WORLD_BASIS,
DODGE_KEY,
+ ATTACK_KEY,
type ThirdPersonControllerData,
type MoveBasis,
} from './ThirdPersonController';
@@ -25,12 +26,32 @@ export {
type ThirdPersonCameraData,
} from './ThirdPersonCamera';
+export {
+ Health,
+ Damage,
+ applyDamage,
+ type HealthData,
+ type DamagePayload,
+} from './Health';
+
+export {
+ MeleeAttack,
+ MeleeAttacks,
+ resolveMeleeHits,
+ COMBAT_ATTACK_START,
+ COMBAT_HIT,
+ COMBAT_ATTACK_END,
+ type MeleeAttackData,
+ type MeleeOverlapQuery,
+} from './MeleeAttack';
+
export {
GameplayPlugin,
gameplayPlugin,
TPC_SPEED,
TPC_GROUNDED,
TPC_DODGE,
+ TPC_ATTACK,
requestMotion,
observeMotion,
updateCameras,
diff --git a/sdk/tests/combat.test.ts b/sdk/tests/combat.test.ts
new file mode 100644
index 000000000..d4722622c
--- /dev/null
+++ b/sdk/tests/combat.test.ts
@@ -0,0 +1,295 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The claim: an animation event, a hit and damage are three different facts, and
+ * one swing lands on one target exactly once.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ Health, Damage, applyDamage, MeleeAttack, MeleeAttacks, resolveMeleeHits,
+ COMBAT_ATTACK_START, COMBAT_HIT, COMBAT_ATTACK_END,
+ type HealthData, type DamagePayload, type MeleeAttackData, type MeleeOverlapQuery,
+} from '../src/gameplay';
+import { Transform, type TransformData } from '../src/ecs/component';
+import type { AnimatorEventPayload } from '../src/animation';
+import type { Entity } from '../src/types';
+
+const ATTACKER = 1 as Entity;
+const ANCHOR = 2 as Entity;
+const NEAR = 3 as Entity;
+const FAR = 4 as Entity;
+const FLOOR = 5 as Entity;
+
+function makeWorld() {
+ const store = new Map<unknown, Map<number, unknown>>();
+ const mapOf = (c: unknown) => {
+ let m = store.get(c);
+ if (!m) { m = new Map(); store.set(c, m); }
+ return m;
+ };
+ return {
+ composed: 0,
+ insert(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },
+ get(e: number, c: unknown) { return mapOf(c).get(e); },
+ has(e: number, c: unknown) { return mapOf(c).has(e); },
+ set(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },
+ valid() { return true; },
+ ensureTransformsComposed() { this.composed++; },
+ update(e: number, c: unknown, edit: (d: any) => void) {
+ const d = mapOf(c).get(e);
+ if (d === undefined) throw new Error('update: entity does not carry it');
+ edit(d); mapOf(c).set(e, d);
+ },
+ getEntitiesWithComponents(comps: unknown[]) {
+ const [first, ...rest] = comps;
+ return [...mapOf(first).keys()].filter(e => rest.every(c => mapOf(c).has(e)));
+ },
+ } as any;
+}
+
+/** An entity standing at a world point, with no local of its own to confuse it. */
+function place(world: any, entity: Entity, x: number, y: number, z: number): void {
+ world.insert(entity, Transform, {
+ position: { x, y, z },
+ worldPosition: { x, y, z },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 },
+ worldScale: { x: 1, y: 1, z: 1 },
+ } as unknown as TransformData);
+}
+
+const health = (current = 100): HealthData => ({ current, max: 100 });
+
+/**
+ * A world with an attacker at the origin, its swing anchor 100 units out along
+ * +X, a target beside the ANCHOR and another beside the ATTACKER — so a query
+ * asked at the wrong place picks the wrong one.
+ */
+function scene(over: Partial<MeleeAttackData> = {}) {
+ const world = makeWorld();
+ place(world, ATTACKER, 0, 0, 0);
+ place(world, ANCHOR, 100, 0, 0);
+ place(world, NEAR, 110, 0, 0);
+ place(world, FAR, 10, 0, 0);
+ place(world, FLOOR, 100, -10, 0);
+ world.insert(NEAR, Health, health());
+ world.insert(FAR, Health, health());
+ world.insert(ATTACKER, Health, health());
+ world.insert(ATTACKER, MeleeAttack, {
+ radius: 40, damage: 25, layers: 0, anchor: ANCHOR,
+ enabled: true, attackId: 0, hitCount: 0, ...over,
+ } as MeleeAttackData);
+ return world;
+}
+
+/** A physics world that answers with whoever is inside the sphere it was asked
+ * about — including the floor and the attacker, which is what a real one does. */
+function physics(world: any, population: Entity[] = [ATTACKER, NEAR, FAR, FLOOR]): MeleeOverlapQuery & { asked: { x: number; y: number; z: number }[] } {
+ const asked: { x: number; y: number; z: number }[] = [];
+ return {
+ asked,
+ overlapSphere(centre, radius) {
+ asked.push({ ...centre });
+ return population
+ .filter((e) => {
+ const p = (world.get(e, Transform) as TransformData).worldPosition!;
+ return Math.hypot(p.x - centre.x, p.y - centre.y, p.z - centre.z) <= radius;
+ })
+ .map((e) => {
+ const p = (world.get(e, Transform) as TransformData).worldPosition!;
+ return { entity: e, x: p.x, y: p.y, z: p.z };
+ });
+ },
+ };
+}
+
+const event = (name: string, entity: Entity = ATTACKER): AnimatorEventPayload =>
+ ({ entity, name, value: 0, text: '' });
+
+/** Collect the blows a run of events produced. */
+function swing(world: any, attacks: MeleeAttacks, names: string[], query = physics(world)): DamagePayload[] {
+ const blows: DamagePayload[] = [];
+ resolveMeleeHits(world, attacks, query, names.map((n) => event(n)), { send: (b) => blows.push(b) });
+ return blows;
+}
+
+const attackData = (world: any) => world.get(ATTACKER, MeleeAttack) as MeleeAttackData;
+
+// =============================================================================
+// Health: one writer
+// =============================================================================
+
+describe('a blow lands in exactly one place', () => {
+ it('takes the amount off, and no lower than nothing', () => {
+ const world = scene();
+ applyDamage(world, [{ target: NEAR, source: ATTACKER, amount: 30, x: 0, y: 0, z: 0 }]);
+ expect((world.get(NEAR, Health) as HealthData).current).toBe(70);
+
+ applyDamage(world, [{ target: NEAR, source: ATTACKER, amount: 999, x: 0, y: 0, z: 0 }]);
+ expect((world.get(NEAR, Health) as HealthData).current).toBe(0);
+ });
+
+ it('passes over anything that has no health to lose', () => {
+ const world = scene();
+ expect(() => applyDamage(
+ world, [{ target: FLOOR, source: ATTACKER, amount: 30, x: 0, y: 0, z: 0 }],
+ )).not.toThrow();
+ expect(world.has(FLOOR, Health)).toBe(false);
+ });
+
+ it('leaves something already down alone', () => {
+ const world = scene();
+ world.insert(NEAR, Health, health(0));
+ applyDamage(world, [{ target: NEAR, source: ATTACKER, amount: 30, x: 0, y: 0, z: 0 }]);
+ expect((world.get(NEAR, Health) as HealthData).current).toBe(0);
+ });
+});
+
+// =============================================================================
+// An animation event is not a hit, and a hit is not damage
+// =============================================================================
+
+describe('where the swing is asked about', () => {
+ it('is the animated anchor, not the character it belongs to', () => {
+ const world = scene();
+ const query = physics(world);
+ const blows = swing(world, new MeleeAttacks(), [COMBAT_ATTACK_START, COMBAT_HIT], query);
+
+ expect(query.asked).toEqual([{ x: 100, y: 0, z: 0 }]);
+ // NEAR stands by the anchor, FAR by the attacker: only one is reachable.
+ expect(blows.map((b) => b.target)).toEqual([NEAR]);
+ });
+
+ it('falls back to the attacker when no anchor is named', () => {
+ const world = scene({ anchor: 0 as Entity });
+ const query = physics(world);
+ const blows = swing(world, new MeleeAttacks(), [COMBAT_HIT], query);
+
+ expect(query.asked).toEqual([{ x: 0, y: 0, z: 0 }]);
+ expect(blows.map((b) => b.target)).toEqual([FAR]);
+ });
+
+ it('makes the composition current first, since the anchor hangs off a joint', () => {
+ const world = scene();
+ swing(world, new MeleeAttacks(), [COMBAT_HIT]);
+ expect(world.composed).toBeGreaterThan(0);
+ });
+});
+
+describe('who a swing may hurt', () => {
+ it('is never the one swinging it', () => {
+ // The attacker is inside its own reach here, and carries Health.
+ const world = scene({ anchor: 0 as Entity, radius: 200 });
+ const blows = swing(world, new MeleeAttacks(), [COMBAT_HIT]);
+ expect(blows.map((b) => b.target)).not.toContain(ATTACKER);
+ });
+
+ it('is never something with no health — the floor is a collider too', () => {
+ const world = scene({ anchor: 0 as Entity, radius: 500 });
+ const blows = swing(world, new MeleeAttacks(), [COMBAT_HIT]);
+ expect(blows.map((b) => b.target).sort((a, b) => a - b)).toEqual([NEAR, FAR]);
+ });
+
+ it('is decided here, not by the physics world it asked', () => {
+ // The query is told to answer with everything, wherever it is.
+ const world = scene();
+ const everything: MeleeOverlapQuery = {
+ overlapSphere: () => [ATTACKER, NEAR, FAR, FLOOR].map((e) => ({ entity: e, x: 0, y: 0, z: 0 })),
+ };
+ const blows = swing(world, new MeleeAttacks(), [COMBAT_HIT], everything as never);
+ expect(blows.map((b) => b.target).sort((a, b) => a - b)).toEqual([NEAR, FAR]);
+ });
+});
+
+describe('one swing lands once', () => {
+ it('however many times the clip says it connects', () => {
+ const world = scene();
+ const attacks = new MeleeAttacks();
+ const blows = swing(world, attacks, [COMBAT_ATTACK_START, COMBAT_HIT, COMBAT_HIT, COMBAT_HIT]);
+ expect(blows.length).toBe(1);
+ expect(attackData(world).hitCount).toBe(1);
+ });
+
+ it('and the next swing may land again', () => {
+ const world = scene();
+ const attacks = new MeleeAttacks();
+ const first = swing(world, attacks, [COMBAT_ATTACK_START, COMBAT_HIT, COMBAT_ATTACK_END]);
+ const firstId = attackData(world).attackId;
+ const second = swing(world, attacks, [COMBAT_ATTACK_START, COMBAT_HIT]);
+
+ expect(first.length).toBe(1);
+ expect(second.length).toBe(1);
+ expect(attackData(world).attackId).not.toBe(firstId);
+ });
+
+ it('even when the clip declares no start of its own', () => {
+ const world = scene();
+ const attacks = new MeleeAttacks();
+ expect(swing(world, attacks, [COMBAT_HIT, COMBAT_HIT]).length).toBe(1);
+ expect(attackData(world).attackId).toBeGreaterThan(0);
+ });
+
+ it('and the swing is over when the clip says so', () => {
+ const world = scene();
+ const attacks = new MeleeAttacks();
+ swing(world, attacks, [COMBAT_ATTACK_START, COMBAT_HIT, COMBAT_ATTACK_END]);
+ expect(attackData(world).attackId).toBe(0);
+ expect(attackData(world).hitCount).toBe(0);
+ });
+});
+
+describe('what the animator says is not what combat does', () => {
+ it('ignores an event from something that cannot swing', () => {
+ const world = scene();
+ const blows: DamagePayload[] = [];
+ resolveMeleeHits(world, new MeleeAttacks(), physics(world),
+ [event(COMBAT_HIT, NEAR)], { send: (b) => blows.push(b) });
+ expect(blows).toEqual([]);
+ });
+
+ it('ignores every event name it was not told to care about', () => {
+ const world = scene();
+ expect(swing(world, new MeleeAttacks(), ['footstep', 'windup', 'recover'])).toEqual([]);
+ });
+
+ it('does nothing at all while the attack is disabled', () => {
+ const world = scene({ enabled: false });
+ expect(swing(world, new MeleeAttacks(), [COMBAT_ATTACK_START, COMBAT_HIT])).toEqual([]);
+ });
+});
+
+describe('what a blow carries', () => {
+ it('is who dealt it, how much, and where it landed', () => {
+ const world = scene();
+ const [blow] = swing(world, new MeleeAttacks(), [COMBAT_HIT]);
+ expect(blow).toEqual({
+ target: NEAR, source: ATTACKER, amount: 25, x: 110, y: 0, z: 0,
+ });
+ });
+
+ it('and the damage is the attack’s, so two attackers hit differently', () => {
+ const world = scene({ damage: 7 });
+ expect(swing(world, new MeleeAttacks(), [COMBAT_HIT])[0].amount).toBe(7);
+ });
+});
+
+describe('the whole way through', () => {
+ it('an event becomes a query becomes a blow becomes health', () => {
+ const world = scene();
+ const blows = swing(world, new MeleeAttacks(), [COMBAT_ATTACK_START, COMBAT_HIT]);
+ expect((world.get(NEAR, Health) as HealthData).current).toBe(100);
+ applyDamage(world, blows);
+ expect((world.get(NEAR, Health) as HealthData).current).toBe(75);
+ expect((world.get(FAR, Health) as HealthData).current).toBe(100);
+ });
+
+ it('and the Damage bus is the seam between the two halves', () => {
+ // Nothing in combat writes Health: the resolve above changed nothing
+ // until applyDamage ran, which is the whole of this claim.
+ const world = scene();
+ swing(world, new MeleeAttacks(), [COMBAT_ATTACK_START, COMBAT_HIT]);
+ expect((world.get(NEAR, Health) as HealthData).current).toBe(100);
+ expect(Damage).toBeDefined();
+ });
+});