-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement Pythagorean theorem for closest entity calculation
- Loading branch information
Showing
3 changed files
with
63 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,33 @@ | ||
import { Entity } from "../entities/Entity"; | ||
import { positionAsNumber } from "../Position"; | ||
|
||
export interface ClosestEntityScore { | ||
score: number; | ||
distance: number; | ||
target: Entity; | ||
} | ||
|
||
export function closestEntity(entity: Entity, targets: Entity[]): Entity { | ||
const entityPosition = positionAsNumber(entity.getPosition()); | ||
const entityPosition = entity.getPosition(); | ||
const x1 = entityPosition.x; | ||
const y1 = entityPosition.y; | ||
const scores: ClosestEntityScore[] = []; | ||
|
||
for (const target of targets) { | ||
if (target.dead()) { | ||
continue; | ||
} | ||
|
||
const targetPosition = positionAsNumber(target.getPosition()); | ||
const score = Math.abs(entityPosition - targetPosition); | ||
const targetPosition = target.getPosition(); | ||
const x2 = targetPosition.x; | ||
const y2 = targetPosition.y; | ||
const distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); | ||
|
||
scores.push({ target, score }); | ||
scores.push({ distance, target }); | ||
} | ||
|
||
if (scores.length === 0) { | ||
throw new Error("No alive targets found"); | ||
} | ||
|
||
scores.sort((a, b) => a.score - b.score); | ||
scores.sort((a, b) => a.distance - b.distance); | ||
return scores[0].target; | ||
} |