Files
esengine/extensions/cocos/cocos-ecs/assets/scripts/ecs/systems/MovementSystem.ts

99 lines
3.4 KiB
TypeScript
Raw Normal View History

2025-06-17 00:32:16 +08:00
import { EntitySystem, Entity, Matcher, Time } from '@esengine/ecs-framework';
import { PositionComponent } from '../components/PositionComponent';
import { VelocityComponent } from '../components/VelocityComponent';
/**
* -
*
* EntitySystem示例
* 1. 使Matcher指定需要的组件Position + Velocity
* 2.
* 3.
*/
export class MovementSystem extends EntitySystem {
constructor() {
// 只处理同时拥有PositionComponent和VelocityComponent的实体
super(Matcher.empty().all(PositionComponent, VelocityComponent));
}
/**
*
*/
protected process(entities: Entity[]): void {
for (const entity of entities) {
const position = entity.getComponent(PositionComponent);
const velocity = entity.getComponent(VelocityComponent);
// 基本移动:位置 = 当前位置 + 速度 * 时间
position.move(
velocity.velocity.x * Time.deltaTime,
velocity.velocity.y * Time.deltaTime,
velocity.velocity.z * Time.deltaTime
);
// 应用阻尼(摩擦力)
velocity.applyDamping(Time.deltaTime);
// 可选:添加边界检查
this.checkBoundaries(position, velocity);
}
}
/**
*
*
*/
private checkBoundaries(position: PositionComponent, velocity: VelocityComponent) {
const bounds = {
left: -400,
right: 400,
top: 300,
bottom: -300
};
// 检查X轴边界
if (position.position.x < bounds.left) {
position.position.x = bounds.left;
velocity.velocity.x = Math.abs(velocity.velocity.x); // 反弹
} else if (position.position.x > bounds.right) {
position.position.x = bounds.right;
velocity.velocity.x = -Math.abs(velocity.velocity.x); // 反弹
}
// 检查Y轴边界
if (position.position.y < bounds.bottom) {
position.position.y = bounds.bottom;
velocity.velocity.y = Math.abs(velocity.velocity.y); // 反弹
} else if (position.position.y > bounds.top) {
position.position.y = bounds.top;
velocity.velocity.y = -Math.abs(velocity.velocity.y); // 反弹
}
}
/**
*
*
*/
public initialize(): void {
super.initialize();
console.log("MovementSystem 已初始化 - 开始处理实体移动");
}
/**
*
*/
public getStats(): { processedEntities: number; totalMovement: number } {
let totalMovement = 0;
const entities = this.entities;
for (const entity of entities) {
const position = entity.getComponent(PositionComponent);
totalMovement += position.getMovementDistance();
}
return {
processedEntities: entities.length,
totalMovement: totalMovement
};
}
}