移动
/**
* 移动到目标
* @param dt
*/
moveToTarget(dt: number) {
let targetPos = this._findTarget.getPosition();
let nodePos = this.node.getPosition();
let vector = new Vec3();
Vec3.subtract(vector, targetPos, nodePos);
let dir = vector.normalize();
let moveVec = dir.multiplyScalar(this._moveSpeed * dt);
let temPos = this.node.getPosition().add(moveVec);
this.setHeroDir(dir);
//设置武器指向
this.setWeaponAngle(dir);
//检测是否有障碍
if (!this.checkBlockObstacle(temPos, dir)) {
//检测是否到达目标位置
if (this.checkToTarget(temPos)) {
//开始攻击
this._isAttacking = true;
}
this.node.setPosition(this.node.getPosition().add(moveVec));
}
}
怪物分散
public repulsionRadius: number = 80; // 排斥作用半径
public repulsionForce: number = 100; // 排斥力度
// 排斥力计算
private applyRepulsion(dt: number) {
const allMonsters = MapData.Instance.getAllMonsterItems();
const currentPos = this.node.getPosition();
for (const monster of allMonsters) {
if (monster.uuid === this.node.uuid) continue;
let targetPos = monster.getPosition();
let vector = new Vec3();
Vec3.subtract(vector, currentPos, targetPos);
let distance = vector.length();
let dir = distance > 0 ? vector.clone().normalize() : new Vec3(Math.random() - 0.5, Math.random() - 0.5, 0,);
if (distance < this.repulsionRadius && distance >= 0) {
// 距离越近排斥力越大
if (!this._isAttacking) {
const force = (1 - distance / this.repulsionRadius) * this.repulsionForce;
let moveVec = dir.multiplyScalar(force * dt);
this.node.setPosition(this.node.getPosition().add(moveVec));
}
}
}
}
protected childUpdate(dt: number): void {
// 排斥力
this.applyRepulsion(dt);
}