Files
esengine/extensions/cocos/cocos-ecs/assets/scripts/ecs/components/VelocityComponent.ts

94 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-06-17 00:32:16 +08:00
import { Component } from '@esengine/ecs-framework';
import { Vec3 } from 'cc';
/**
* -
*
*
* 1. PositionComponent分离
* 2.
* 3.
*/
export class VelocityComponent extends Component {
/** 当前速度向量 */
public velocity: Vec3 = new Vec3();
/** 最大速度限制 */
public maxSpeed: number = 100;
/** 阻尼系数0-11为无阻尼 */
public damping: number = 1.0;
constructor(x: number = 0, y: number = 0, z: number = 0, maxSpeed: number = 100) {
super();
this.velocity.set(x, y, z);
this.maxSpeed = maxSpeed;
}
/**
*
*/
setVelocity(x: number, y: number, z: number = 0) {
this.velocity.set(x, y, z);
this.clampToMaxSpeed();
}
/**
*
*/
addVelocity(x: number, y: number, z: number = 0) {
this.velocity.x += x;
this.velocity.y += y;
this.velocity.z += z;
this.clampToMaxSpeed();
}
/**
*
*/
applyDamping(deltaTime: number) {
if (this.damping < 1.0) {
const dampingFactor = Math.pow(this.damping, deltaTime);
this.velocity.multiplyScalar(dampingFactor);
}
}
/**
*
*/
private clampToMaxSpeed() {
const speed = this.velocity.length();
if (speed > this.maxSpeed) {
this.velocity.normalize();
this.velocity.multiplyScalar(this.maxSpeed);
}
}
/**
*
*/
getSpeed(): number {
return this.velocity.length();
}
/**
*
*/
getDirection(): Vec3 {
const result = new Vec3();
Vec3.normalize(result, this.velocity);
return result;
}
/**
*
*/
stop() {
this.velocity.set(0, 0, 0);
}
/**
*
*/
isMoving(): boolean {
return this.velocity.lengthSqr() > 0.01; // 避免浮点数精度问题
}
}