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

102 lines
2.6 KiB
TypeScript
Raw Normal View History

2025-06-17 00:32:16 +08:00
import { Component } from '@esengine/ecs-framework';
/**
* -
*
*
* 1.
* 2.
* 3.
*/
export class HealthComponent extends Component {
/** 最大生命值 */
public maxHealth: number;
/** 当前生命值 */
public currentHealth: number;
/** 生命值回复速度(每秒回复量) */
public regenRate: number = 0;
/** 最后受到伤害的时间(用于延迟回血等机制) */
public lastDamageTime: number = 0;
/** 是否无敌 */
public invincible: boolean = false;
/** 无敌持续时间 */
public invincibleDuration: number = 0;
constructor(maxHealth: number = 100, regenRate: number = 0) {
super();
this.maxHealth = maxHealth;
this.currentHealth = maxHealth;
this.regenRate = regenRate;
}
/**
*
*/
isDead(): boolean {
return this.currentHealth <= 0;
}
/**
*
*/
isFullHealth(): boolean {
return this.currentHealth >= this.maxHealth;
}
/**
* 0-1
*/
getHealthPercentage(): number {
return this.currentHealth / this.maxHealth;
}
/**
*
*/
isHealthBelowPercentage(percentage: number): boolean {
return this.getHealthPercentage() < percentage;
}
/**
*
*/
setHealth(health: number) {
this.currentHealth = Math.max(0, Math.min(health, this.maxHealth));
}
/**
*
*/
heal(amount: number) {
this.currentHealth = Math.min(this.currentHealth + amount, this.maxHealth);
}
/**
*
*
*/
takeDamage(damage: number) {
if (this.invincible) return;
this.currentHealth = Math.max(0, this.currentHealth - damage);
this.lastDamageTime = Date.now();
}
/**
*
*/
setInvincible(duration: number) {
this.invincible = true;
this.invincibleDuration = duration;
}
/**
*
*/
reset() {
this.currentHealth = this.maxHealth;
this.invincible = false;
this.invincibleDuration = 0;
this.lastDamageTime = 0;
}
}