Grid navigation and obstacle avoidance for game characters. A* with 4 or 8 directions, weighted terrain, and no corner cutting, path smoothing with line of sight, flow fields for many units chasing one goal (tower defense, RTS, swarms), reachability checks for level validation, converting between tiles and world positions, re-pathing when the map changes, and local avoidance between moving unit...
Download skill (.zip) Files on GitHubPathfinding
Drop-in: assets/pathfind.js (tests: finds paths, avoids walls and slow tiles, never cuts corners, unreachable returns null,
smoothing 13 → 5 waypoints, flow field leads to the goal, 200×200 maze fast).
import { astar, smooth, flowField, lineOfSight, gridFromStrings } from "./core/pathfind.js";
const grid = { w: level.cols, h: level.rows, cost: (x, y) => (level.solid(x, y) ? Infinity : level.mud(x, y) ? 3 : 1) };
let path = astar(grid, tx(e.x), ty(e.y), tx(player.x), ty(player.y)); // [{x, y}] tiles, or null
path = smooth(grid, path)?.map((c) => ({ x: (c.x + 0.5) * TILE, y: (c.y + 0.5) * TILE })); // world waypoints
// follow with enemy-ai steer.followPath(e, path)
const field = flowField(grid, goalX, goalY); // once per goal change
const { dx, dy, dist } = field.at(tx(u.x), ty(u.y)); // every unit: just read the direction
Which one
| Situation | Use |
|---|---|
| A few enemies chasing the player | A* per enemy, re-path every 0.3–1 s or when the player changes tile |
| Many units to one goal (tower defense, swarm, RTS move) | Flow field, once per goal |
| “Can I see / shoot?” | lineOfSight (or collision-detection raycastGrid) |
| Level validation (“is the exit reachable?”) | astar(...) !== null, or procedural-generation isConnected |
| Open space, no walls | Just steer toward the target (enemy-ai) |
Rules
- Re-path on events, not every frame: target moved a tile, a door opened, a tower was placed. Stagger re-paths across enemies.
- Tower defense: before allowing a tower, check that a path still exists (block placements that seal the route).
maxNodes(default 20,000) stops huge searches from freezing a frame. Raise it for big maps, or path over a coarser grid.- Smooth paths for natural movement; keep raw tile paths for grid games.
- Units crowding: add separation steering; give them slightly different targets around the goal.
- Diagonals: no corner cutting (already enforced) so units don’t clip wall corners.