Skip to content

Instantly share code, notes, and snippets.

@trezy
Created March 7, 2023 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trezy/6c7784ecc8ba0493cb137a6838d95bbc to your computer and use it in GitHub Desktop.
Save trezy/6c7784ecc8ba0493cb137a6838d95bbc to your computer and use it in GitHub Desktop.
class MapManager {
findPath(fromX, fromY, toX, toY) {
/**
* With ngraph we don't have to create grid cells if they're unoccupied, so we
* have to verify we're not running the pathfinder against non-existent nodes.
*/
if (this.#graph.hasNode(`${toX}|${toY}`)) {
/**
* It's probably not necessary to generate a new pathfinder every time right
* now, but it'll be valuable in the future when the user gains the ability
* to change to pathfinding algo.
*/
return aStar(this.#graph).find(
`${fromX}|${fromY}`,
`${toX}|${toY}`,
)
}
return null
}
}
class MapManager {
findPath(fromX, fromY, toX, toY) {
/**
* Coordinates are coming from the main map grid, which may not start at
* `0, 0` (i.e. there may be tiles placed in the negative axial space).
*
* Since the pathfinding grid cannot have coordinates in the negative axial
* space, we have to translate our coordinates for the pathfinding grid.
*/
const [
fromPFX,
fromPFY,
] = this.getPFCellCoordinates(fromX, fromY)
const [
toPFX,
toPFY,
] = this.getPFCellCoordinates(toX, toY)
/**
* We have to run the pathfinder on a clone of the grid, otherwise future
* pathfinding will break.
*/
const grid = this.#pathfindingGrid.clone()
const path = this.#finder.findPath(
fromPFX,
fromPFY,
toPFX,
toPFY,
grid,
)
/**
* To wrap things up, we have to translate coordinates back for the main grid.
*/
return path.map(([x, y]) => this.getCellFromPFCoordinates(x, y))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment