Convert Figma logo to code with AI

qiao logoPathFinding.js

A comprehensive path-finding library for grid based games

8,606
1,347
8,606
106

Top Related Projects

A* Search / Pathfinding Algorithm in Javascript

Path finding in a graph

Quick Overview

PathFinding.js is a comprehensive JavaScript library for grid-based pathfinding algorithms. It provides a collection of search algorithms for finding the shortest path between two points on a 2D grid, with support for various grid types and heuristics.

Pros

  • Wide range of pathfinding algorithms implemented, including A*, Dijkstra, BFS, and more
  • Highly customizable with options for different grid types, heuristics, and diagonal movement
  • Includes a visual demo for easy understanding and testing of algorithms
  • Well-documented API and examples for easy integration

Cons

  • Performance may be slower compared to specialized implementations for specific use cases
  • Limited to 2D grid-based pathfinding, not suitable for 3D or non-grid environments
  • Lacks advanced features like dynamic obstacle avoidance or multi-agent pathfinding

Code Examples

  1. Basic usage with A* algorithm:
var grid = new PF.Grid(5, 5);
var finder = new PF.AStarFinder();
var path = finder.findPath(0, 0, 4, 4, grid);
console.log(path);
  1. Using a different algorithm (Dijkstra):
var grid = new PF.Grid(5, 5);
var finder = new PF.DijkstraFinder();
var path = finder.findPath(0, 0, 4, 4, grid);
console.log(path);
  1. Setting walkable nodes:
var grid = new PF.Grid(5, 5);
grid.setWalkableAt(2, 2, false);
var finder = new PF.AStarFinder();
var path = finder.findPath(0, 0, 4, 4, grid);
console.log(path);

Getting Started

  1. Install PathFinding.js using npm:

    npm install pathfinding
    
  2. Import the library in your JavaScript file:

    import PF from 'pathfinding';
    
  3. Create a grid and finder, then find a path:

    const grid = new PF.Grid(10, 10);
    const finder = new PF.AStarFinder();
    const path = finder.findPath(0, 0, 9, 9, grid);
    console.log(path);
    

Competitor Comparisons

A* Search / Pathfinding Algorithm in Javascript

Pros of javascript-astar

  • Lightweight and focused solely on A* pathfinding
  • Simple implementation, easy to understand and modify
  • Efficient for small to medium-sized grids

Cons of javascript-astar

  • Limited to A* algorithm only
  • Lacks advanced features and optimizations
  • Not actively maintained (last update in 2020)

Code Comparison

PathFinding.js:

var finder = new PF.AStarFinder();
var path = finder.findPath(0, 0, 5, 5, grid);

javascript-astar:

var graph = new Graph(grid);
var start = graph.grid[0][0];
var end = graph.grid[5][5];
var result = astar.search(graph, start, end);

Key Differences

PathFinding.js offers a wider range of pathfinding algorithms and grid types, making it more versatile for various scenarios. It also provides better documentation and examples.

javascript-astar is more straightforward and easier to integrate for simple A* pathfinding needs. However, it lacks the flexibility and advanced features of PathFinding.js.

PathFinding.js is actively maintained and has a larger community, which can be beneficial for long-term support and updates.

Use Cases

  • Choose PathFinding.js for projects requiring multiple algorithms or complex pathfinding scenarios
  • Opt for javascript-astar in simpler projects where only A* is needed and minimal overhead is desired

Both libraries have their merits, and the choice depends on the specific requirements of your project.

Path finding in a graph

Pros of ngraph.path

  • Designed for large-scale graph processing, handling millions of nodes efficiently
  • Supports both directed and undirected graphs
  • Flexible API allowing custom graph structures and weight functions

Cons of ngraph.path

  • Limited to A* algorithm implementation
  • Less beginner-friendly documentation compared to PathFinding.js
  • Fewer built-in grid-based pathfinding options

Code Comparison

PathFinding.js:

var finder = new PF.AStarFinder();
var path = finder.findPath(0, 0, 5, 5, grid);

ngraph.path:

var pathFinder = ngraphPath.aStar(graph);
var path = pathFinder.find(fromNodeId, toNodeId);

Key Differences

PathFinding.js focuses on grid-based pathfinding with multiple algorithms, while ngraph.path is tailored for general graph structures with a focus on the A* algorithm. PathFinding.js offers a more intuitive API for grid-based scenarios, whereas ngraph.path provides greater flexibility for custom graph implementations.

PathFinding.js includes visualization tools and is well-suited for smaller-scale pathfinding tasks in games or simple applications. ngraph.path, on the other hand, excels in large-scale graph processing scenarios and offers better performance for complex graph structures.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

PathFinding.js

A comprehensive path-finding library in javascript.

Gitter

Build Status Dependency Status Documentation Status

Introduction

The aim of this project is to provide a path-finding library that can be easily incorporated into web games. It may run on Node.js or the browser.

It comes along with an online demo to show how the algorithms execute. (The pathfinding speed is slowed down in the demo)

Note that this project only provides path-finding algorithms for 2D space. If you need to work in a 3D environment, then you may use @schteppe's fork.

There is new documentation being written for PathFinding.js. You can read it here. Note that this is in very early stages and far from complete so keep your eyes open for mistakes and don't hesitate to open a pull request in case you find one.

Server

If you want to use it in Node.js, you may install it via npm.

npm install pathfinding

Then, in your program:

var PF = require('pathfinding');

See the Basic Usage section below for usage details.

Browser

If you have bower installed then you can install it with the following command:

bower install pathfinding

By default bower will install pathfinding under the bower_components folder, so to include it in your page do something like:

<script type="text/javascript" src="path/to/bower_components/pathfinding/pathfinding-browser.min.js"></script>

You can also grab a release from the Releases Page if you don't use bower.

Basic Usage

To build a grid-map of width 5 and height 3:

var grid = new PF.Grid(5, 3); 

By default, all the nodes in the grid will be able to be walked through. To set whether a node at a given coordinate is walkable or not, use the setWalkableAt method.

For example, to set the node at (0, 1) to be un-walkable, where 0 is the x coordinate (from left to right), and 1 is the y coordinate (from up to down):

grid.setWalkableAt(0, 1, false);

You may also pass in a matrix while instantiating the PF.Grid class. It will initiate all the nodes in the grid with the same walkability indicated by the matrix. 0 for walkable while 1 for blocked.

var matrix = [
    [0, 0, 0, 1, 0],
    [1, 0, 0, 0, 1],
    [0, 0, 1, 0, 0],
];
var grid = new PF.Grid(matrix);

Currently there are 10 path-finders bundled in this library, namely:

  • AStarFinder *
  • BestFirstFinder
  • BreadthFirstFinder *
  • DijkstraFinder *
  • IDAStarFinder.js *
  • JumpPointFinder *
  • OrthogonalJumpPointFinder *
  • BiAStarFinder
  • BiBestFirstFinder
  • BiBreadthFirstFinder *
  • BiDijkstraFinder *

The prefix Bi for the last four finders in the above list stands for the bi-directional searching strategy.

Also, Note that only the finders with trailing asterisks are guaranteed to find the shortest path.

To build a path-finder, say, the AStarFinder:

var finder = new PF.AStarFinder();

To find a path from (1, 2) to (4, 2), (Note: both the start point and end point should be walkable):

var path = finder.findPath(1, 2, 4, 2, grid);

path will be an array of coordinates including both the start and end positions.

For the matrix defined previously, the path will be:

[ [ 1, 2 ], [ 1, 1 ], [ 2, 1 ], [ 3, 1 ], [ 3, 2 ], [ 4, 2 ] ]

Be aware that grid will be modified in each path-finding, and will not be usable afterwards. If you want to use a single grid multiple times, create a clone for it before calling findPath.

var gridBackup = grid.clone();

Advanced Usage

When instantiating path-finders, you may pass in additional parameters to indicate which specific strategies to use.

For all path-finders, you may indicate whether diagonal movement is allowed. The default value is false, which means that the path can only go orthogonally.

In order to enable diagonal movement:

var finder = new PF.AStarFinder({
    allowDiagonal: true
});

When diagonal movement is enabled, you might want to prevent the path from touching the corners of the occupied grid blocks. This is usually desirable if the objects using the path have physical width and can also move between the grid cells.

To enable the corner crossing prevention:

var finder = new PF.AStarFinder({
    allowDiagonal: true,
    dontCrossCorners: true
});

Note that dontCrossCorners only makes sense when allowDiagonal is also used. Currently all algorithms except JumpPointFinder support this feature.

For AStarFinder, BestFirstFinder and all their Bi relatives, you may indicate which heuristic function to use.

The predefined heuristics are PF.Heuristic.manhattan(default), PF.Heuristic.chebyshev, PF.Heuristic.euclidean and PF.Heuristic.octile.

To use the chebyshev heuristic:

var finder = new PF.AStarFinder({
    heuristic: PF.Heuristic.chebyshev
});

To build a BestFirstFinder with diagonal movement allowed and a custom heuristic function:

var finder = new PF.BestFirstFinder({
    allowDiagonal: true,
    heuristic: function(dx, dy) {
        return Math.min(dx, dy);
    }
});

To smoothen the path, you may use PF.Util.smoothenPath. This routine will return a new path with the original one unmodified.

var newPath = PF.Util.smoothenPath(grid, path);

Note that the new path will be compressed as well, i.e. if the original path is [[0, 1], [0, 2], [0, 3], [0, 4]], then the new path will be [[0, 1], [0, 4]].

To just compress a path without smoothing it, you may use PF.Util.compressPath.

var newPath = PF.Util.compressPath(path);

To expand the compressed path like [[0, 1], [0, 4]] back to [[0, 1], [0, 2], [0, 3], [0, 4]], you may use PF.Util.expandPath.

var newPath = PF.Util.expandPath(path);

Development

Layout:

.
|-- lib          # browser distribution
|-- src          # source code (algorithms only)
|-- test         # test scripts
|-- utils        # build scripts
|-- benchmark    # benchmarks
`-- visual       # visualization

Make sure you have node.js installed, then use npm to install the dependencies:

npm install -d 

The build system uses gulp, so make sure you have it installed:

npm install -d -g gulp

To build the browser distribution:

gulp compile

To run the tests (algorithms only, not including the visualization) with mocha and should.js First install mocha:

npm install -d -g mocha

Then run the tests:

gulp test

To run the benchmarks:

gulp bench

Or if you are feeling lazy, the default gulp task does everything(except running the benchmarks):

gulp

License

MIT License

© 2011-2012 Xueqiao Xu <xueqiaoxu@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

NPM DownloadsLast 30 Days