|
| 1 | +import { World } from "../../src/world"; |
| 2 | +import { createComponentId } from "../../src/entity"; |
| 3 | +import type { System } from "../../src/system"; |
| 4 | +import type { Query } from "../../src/query"; |
| 5 | + |
| 6 | +// 定义组件类型 |
| 7 | +type Position = { x: number; y: number }; |
| 8 | +type Velocity = { x: number; y: number }; |
| 9 | + |
| 10 | +// 定义组件ID |
| 11 | +const PositionId = createComponentId<Position>(1); |
| 12 | +const VelocityId = createComponentId<Velocity>(2); |
| 13 | + |
| 14 | +// 移动系统 |
| 15 | +class MovementSystem implements System { |
| 16 | + private query: Query; // 缓存查询 |
| 17 | + |
| 18 | + constructor(world: World) { |
| 19 | + // 在构造函数中预先创建并缓存查询 |
| 20 | + this.query = world.createQuery([PositionId, VelocityId]); |
| 21 | + } |
| 22 | + |
| 23 | + update(world: World, deltaTime: number): void { |
| 24 | + // 使用缓存的查询的forEach方法,直接获取组件数据 |
| 25 | + this.query.forEach([PositionId, VelocityId], (entity, position, velocity) => { |
| 26 | + // 更新位置 |
| 27 | + position.x += velocity.x * deltaTime; |
| 28 | + position.y += velocity.y * deltaTime; |
| 29 | + |
| 30 | + console.log(`Entity ${entity}: Position (${position.x.toFixed(2)}, ${position.y.toFixed(2)})`); |
| 31 | + }); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +function main() { |
| 36 | + console.log("ECS Simple Demo"); |
| 37 | + |
| 38 | + // 创建世界 |
| 39 | + const world = new World(); |
| 40 | + |
| 41 | + // 注册系统(传递world参数) |
| 42 | + world.registerSystem(new MovementSystem(world)); |
| 43 | + |
| 44 | + // 创建实体1 |
| 45 | + const entity1 = world.createEntity(); |
| 46 | + world.addComponent(entity1, PositionId, { x: 0, y: 0 }); |
| 47 | + world.addComponent(entity1, VelocityId, { x: 1, y: 0.5 }); |
| 48 | + |
| 49 | + // 创建实体2 |
| 50 | + const entity2 = world.createEntity(); |
| 51 | + world.addComponent(entity2, PositionId, { x: 10, y: 10 }); |
| 52 | + world.addComponent(entity2, VelocityId, { x: -0.5, y: 1 }); |
| 53 | + |
| 54 | + // 执行命令以应用组件添加 |
| 55 | + world.flushCommands(); |
| 56 | + |
| 57 | + // 运行几个更新循环 |
| 58 | + const deltaTime = 1.0; // 1秒 |
| 59 | + for (let i = 0; i < 5; i++) { |
| 60 | + console.log(`\nUpdate ${i + 1}:`); |
| 61 | + world.update(deltaTime); |
| 62 | + } |
| 63 | + |
| 64 | + console.log("\nDemo completed!"); |
| 65 | +} |
| 66 | + |
| 67 | +// 运行demo |
| 68 | +main(); |
0 commit comments