victor's picture
victor HF Staff
Refactor tower system and UI improvements
9e6ef9c
export function findNearestWithinRange(tower, enemies) {
let nearest = null;
let nearestDistSq = Infinity;
for (const e of enemies) {
const dSq = e.mesh.position.distanceToSquared(tower.position);
if (dSq <= tower.range * tower.range && dSq < nearestDistSq) {
nearest = e;
nearestDistSq = dSq;
}
}
return nearest;
}
export function findClosestToExitInRange(tower, enemies) {
const inRange = [];
const rangeSq = tower.range * tower.range;
for (const e of enemies) {
const dSq = e.mesh.position.distanceToSquared(tower.position);
if (dSq <= rangeSq) {
inRange.push(e);
}
}
if (inRange.length === 0) return null;
const towerPos = tower.position;
inRange.sort((a, b) => {
const segA = a.currentSeg ?? 0;
const segB = b.currentSeg ?? 0;
if (segA !== segB) return segB - segA;
const remA = a.target
? a.target.distanceTo(a.position ?? a.mesh.position)
: Infinity;
const remB = b.target
? b.target.distanceTo(b.position ?? b.mesh.position)
: Infinity;
if (remA !== remB) return remA - remB;
const da = (a.mesh?.position || a.position).distanceTo(towerPos);
const db = (b.mesh?.position || b.position).distanceTo(towerPos);
return da - db;
});
return inRange[0] || null;
}
export function findMultipleInRangeOrdered(tower, enemies, priority = "nearest") {
const rangeSq = tower.range * tower.range;
const inRange = [];
for (const e of enemies) {
const dSq = e.mesh.position.distanceToSquared(tower.position);
if (dSq <= rangeSq) inRange.push(e);
}
if (inRange.length === 0) return [];
if (priority === "closestToExit") {
const towerPos = tower.position;
inRange.sort((a, b) => {
const segA = a.currentSeg ?? 0;
const segB = b.currentSeg ?? 0;
if (segA !== segB) return segB - segA;
const remA = a.target
? a.target.distanceTo(a.position ?? a.mesh.position)
: Infinity;
const remB = b.target
? b.target.distanceTo(b.position ?? b.mesh.position)
: Infinity;
if (remA !== remB) return remA - remB;
const da = (a.mesh?.position || a.position).distanceTo(towerPos);
const db = (b.mesh?.position || b.position).distanceTo(towerPos);
return da - db;
});
} else {
const towerPos = tower.position;
inRange.sort((a, b) => {
const da = (a.mesh?.position || a.position).distanceTo(towerPos);
const db = (b.mesh?.position || b.position).distanceTo(towerPos);
return da - db;
});
}
return inRange;
}