nav2d

Nav2d

npm version License: MIT minzipped size Tests codecov

This is a high-quality implementation of a 2D polygonal navigation mesh with A* path finding and funneling (e.g. finding not only the mesh nodes but also the actual path across polygons).

Path finding examples

Why this package

This package was created due to the lack of generic 2D navigation mesh packages able to handle polygonal nodes of any shape and integrating a robust funnel algorithm. Furthermore, some packages require specific file formats for the meshes, limiting the choices of editors.

This package aims to:

Install

There are multiple ways to install nav2d. If you are using npm, and building your game with wepback, you can install and use the package directly:

$ npm i nav2d

You can also directly include the library from the unpkg CDN into your page. There are two options here,

  1. You can use the version containing only the code of this library (you’ll have to include all dependencies yourself):

     <script defer src="https://unpkg.com/nav2d/dist/nav2d.min.js"></script>
    
  2. You can use the deps bundle, which ships together with all dependencies, for hassle free experience:

     <script defer src="https://unpkg.com/nav2d/dist/nav2d_deps.min.js"></script>
    

How to use

First create the navigation mesh, by passing an array of polygons, each polygon being an array of points. Polygons that are not triangles will be triangulated automatically.

import { NavMesh } from "nav2d";

const navmesh = new NavMesh([
    [
        [0, 0],
        [0, 12],
        [12, 0],
    ],
    [
        [12, 8],
        [12, 4],
        [16, 6],
    ],
    [
        [12, 0],
        [6, 6],
        [12, 6],
    ],
    [
        [100, 100],
        [110, 100],
        [100, 110],
        [95, 107],
        [105, 102],
    ],
]);

You can pass points as arrays [x, y], as objects {x:x, y:y} or as Point(x, y) objects.

Warning: Instantiating the NavMesh object can be slow if you have a big mesh with lots of polygons, as the constructor has to triangulate the polygons and creates a neighbors cache to speed up neighbor lookup when searching. This is a one-time cost (e.g. the NavMesh class is optimized to be instantiated once and use multiple times). Ballpark performance numbers are 1.5 seconds for 1000 polygons and 15 seconds for 10_000 polygons (linearly dependent on polygon count).

If your mesh is made up of only triangles, for instance because you use an external triangulation algorithm, you can use new NavMesh(polygons, { triangulate: false }) to skip it, but there will still be some cost in caching neighboring triangles. If you disable triangulation on a mesh which isn’t made of triangles, the library will return wrong results.

For games where the mesh is always the same (for instance the map does not change), the best option is to triangulate the navigation mesh when you create the map, load the map already triangulated and disable triangulation. This will be the fastest.

Now we can query paths:

const path = navmesh.findPath([1, 1], [14, 6]);
console.log(path); // -> [Point(1, 1), Point(14, 6)]

As you can see from the output, thanks to the funnel algorithm, the path will only contain the necessary path points (in this case a straight line). If no path can be found (disconnected islands or endpoints outside the mesh) null will be returned.

Warning: The path quality heavily depends on the quality of the triangulation. If your mesh has a lot of skinny triangles, it might not choose the path you would expect.

nav2d automatically triangulates the mesh with earcut, which is fast but sometimes generates non-optimal triangulations. If you have this problem, you can try triangulating your mesh manually with a library such as poly2tri, as some user successfully did.

If you manually triangulate, make sure to disable triangulation using the new NavMesh(polygons, { triangulate: false }) option to avoid unnecessary work.

To find the path, a optimized A* implementation is used. You can override the default the cost and heuristic functions, by passing an options object to the NavMesh constructor. For example, to implement a simpler breadth first search, we can do:

const costFunc = (polygon1, polygon2, portal) => 1;
const heuristicFunc = () => (polygon, to) => 0;
const navmesh = new NavMesh([...], { costFunc, heuristicFunc });
// Use as before

Instead, to implement Dijkstra’s Algorithm, you can:

const heuristicFunc = () => (polygon, to) => 0;
const navmesh = new NavMesh(
    [...],
    { heuristicFunc }
);

(Look here for an nice explanation of the algorithms above)

The cost function takes two neighboring polygons and a portal as parameters and returns the cost to go from the first to the second. Both polygons are Polygon objects. The portal is the edge shared between the two polygons.

The heuristic function takes two polygon: a polygon on the path and the final polygon, and returns an estimation of the distance between the two. Both of these are Polygon objects.

Note: The default functions compute the distance between polygons using the .centroidDistance() method (see below). This computes the Cartesian distance between the centroids.

This is basically it. This package does nothing more and nothing less.

The Editor

For those looking for an easy way to create, view and edit their navigation meshes, nav2d comes with a simple mesh viewer and editor, where you can also test the path finding.

The editor is accessible here

Editor screenshot

The editor lets you load, visualize and edit navigation meshes and then export the result. It also comes with built-in path finding, so that you can test your routes.

Editor path finding

To help while editing, a powerful snapping feature is also included.

Editor snap feature

API Reference

Point or Vector (aliases)

Note: In all places where points are accepted, nav2d also accepts arrays [x, y] or { x: x, y: y } objects.

Properties:

Methods:

Functions:

Edge

Properties:

Methods:

Polygon

Properties:

Methods:

Properties:

Methods:

Changelog

See here.