@@ -88,6 +88,63 @@ world.set(entity, PositionId, { x: 0, y: 0 });
8888world .sync (); // 钩子在这里被调用
8989```
9090
91+ ### 多组件生命周期钩子
92+
93+ ECS 还支持多组件生命周期钩子,可以监听多个组件同时存在于实体时的事件。只有当所有必需组件都存在时才会触发回调。
94+
95+ ``` typescript
96+ // 定义组件类型
97+ type Position = { x: number ; y: number };
98+ type Velocity = { x: number ; y: number };
99+
100+ // 定义组件ID
101+ const PositionId = component <Position >();
102+ const VelocityId = component <Velocity >();
103+
104+ // 注册多组件生命周期钩子
105+ world .hook ([PositionId , VelocityId ], {
106+ on_init : (entityId , componentTypes , components ) => {
107+ // 当钩子注册时,为已同时拥有 Position 和 Velocity 组件的实体调用
108+ console .log (` 实体 ${entityId } 同时拥有 Position 和 Velocity 组件 ` );
109+ },
110+ on_set : (entityId , componentTypes , components ) => {
111+ // 当实体同时拥有 Position 和 Velocity 组件时调用
112+ const [position, velocity] = components ;
113+ console .log (
114+ ` 实体 ${entityId } 现在同时拥有 Position (${position .x }, ${position .y }) 和 Velocity (${velocity .x }, ${velocity .y }) ` ,
115+ );
116+ },
117+ on_remove : (entityId , componentTypes , components ) => {
118+ // 当实体失去 Position 或 Velocity 组件之一时调用(如果之前同时拥有两者)
119+ const [position, velocity] = components ; // 移除前的组件值快照
120+ console .log (` 实体 ${entityId } 失去了 Position 或 Velocity 组件 ` );
121+ },
122+ });
123+
124+ // 添加组件
125+ const entity = world .new ();
126+ world .set (entity , PositionId , { x: 0 , y: 0 });
127+ world .set (entity , VelocityId , { x: 1 , y: 0.5 });
128+ world .sync (); // 多组件钩子在这里被调用
129+ ```
130+
131+ 还可以使用可选组件,这样即使某些组件不存在也会触发钩子:
132+
133+ ``` typescript
134+ // 注册包含可选组件的多组件生命周期钩子
135+ world .hook ([PositionId , { optional: VelocityId }], {
136+ on_set : (entityId , componentTypes , components ) => {
137+ // 当实体拥有 Position 组件时调用,Velocity 组件可选
138+ const [position, velocity] = components ;
139+ if (velocity !== undefined ) {
140+ console .log (` 实体 ${entityId } 拥有 Position 和 Velocity 组件 ` );
141+ } else {
142+ console .log (` 实体 ${entityId } 仅拥有 Position 组件 ` );
143+ }
144+ },
145+ });
146+ ```
147+
91148### 通配符关系生命周期钩子
92149
93150ECS 还支持通配符关系生命周期钩子,可以监听特定组件的所有关系变化:
0 commit comments