easystarjs

repository·master·Indexed 23 days ago

https://github.com/prettymuchbryce/easystarjs

An asynchronous A* pathfinding library for HTML5 games and interactive projects. Version 0.4.4 provides an API to define walkable grids, set tile and point costs, and configure movement rules such as diagonal movement and corner cutting. It prevents main-thread blocking by calculating paths in chunks via a manual calculate() loop, though it also supports a synchronous mode.

Tokens
3K
Snippets
3
Records
22
Agent score
81%

What's inside easystarjs

  1. Initialize EasyStar.js

    master

    To use the library, you must first create an instance of EasyStar.js. The initialization method differs based on your runtime.

    Web (Browser):

    var easystar = new EasyStar.js();

    Node.js:

    var easystarjs = require('easystarjs');
    var easystar = new easystarjs.js();
    // for node.js
    var easystarjs = require('easystarjs');
    var easystar = new easystarjs.js();
  2. Find a path using EasyStar.js

    master

    To find a path, you must follow these steps:

    1. Set the Grid: Provide a two-dimensional array representing your map.
    2. Set Acceptable Tiles: Define which tile values are walkable.
    3. Request a Path: Call findPath(startX, startY, endX, endY, callback). The callback receives the path (an array of points) or null if no path is found.
    4. Trigger Calculation: Crucially, EasyStar does not calculate automatically. You must call easystar.calculate() (ideally on a ticker or setInterval) to process the pathfinding asynchronously.

    To prevent performance issues on large grids, you can limit the work done per tick using setIterationsPerCalculation(value).

    var grid = [[0,0,1,0,0],
                [0,0,1,0,0],
                [0,0,1,0,0],
                [0,0,1,0,0],
                [0,0,0,0,0]];
    
    easystar.setGrid(grid);
    easystar.setAcceptableTiles([0]);
    
    easystar.findPath(0, 0, 4, 0, function( path ) {
    	if (path === null) {
    		alert("Path was not found.");
    	} else {
    		alert("Path was found. The first Point is " + path[0].x + " " + path[0].y);
    	}
    });
    
    // You must call this to start the asynchronous calculation
    easystar.calculate();
  3. How asynchronous pathfinding works with calculate()

    master

    By default, findPath() schedules a calculation that runs in chunks to avoid freezing the browser/environment. To actually process the pathfinding queue, you must call calculate() manually in your application loop (e.g., inside a requestAnimationFrame or a setInterval).

    Each call to calculate() performs a set number of iterations. You can control this workload using setIterationsPerCalculation(n).

    Workflow:

    1. Call findPath(...) to add a request to the queue.
    2. Call calculate() repeatedly in your game/app loop.
    3. The callback provided to findPath will trigger once the path is found or impossible.
  4. Configure the EasyStar grid and walkable tiles

    master

    To use EasyStar, you must first define which tiles in your grid are considered "walkable" and provide the grid itself.

    1. Set acceptable tiles: Use setAcceptableTiles() to specify which tile values are walkable. You can pass a single number or an array of numbers.
    2. Set the grid: Use setGrid() to provide a 2D array of numbers representing your map.

    If you do not call these methods before calling findPath(), the library will throw an error.

  5. Reference: Main EasyStar.js Methods

    master

    The following are the primary methods available on an EasyStar.js instance:

    • new EasyStar.js(): Constructor.
    • setGrid(twoDimensionalArray): Sets the map grid.
    • setAcceptableTiles(arrayOfAcceptableTiles): Defines walkable tiles.
    • findPath(startX, startY, endX, endY, callback): Requests a path. Returns an instanceId if used with the ID-based signature.
    • calculate(): Starts/continues the asynchronous calculation process.
    • cancelPath(instanceId): Cancels a specific pathfinding task.
  6. Configure the EasyStar pathfinding engine

    master

    EasyStar is a pathfinding library that uses the A* algorithm to find paths through a grid. To use it, you must first define the grid and the acceptable tiles (walkable areas).

    Core Configuration Tasks

    • Set the Grid: Define the dimensions and structure of your world using setGrid(grid). The grid should be a 2D array.
    • Define Walkable Tiles: Use setAcceptableTiles(tiles) to specify which tile values are passable. You can pass a single number or an array of numbers.
    • Set Tile Costs: Use setTileCost(tile, cost) to assign specific weights to certain tiles, making some paths more
  7. Configure pathfinding behavior

    master

    EasyStar provides several methods to customize how paths are calculated and how the environment is treated:

    • Movement Rules:

      • enableDiagonals(): Allows diagonal movement.
      • enableCornerCutting(): Allows cutting through corners.
      • setDirectionalCondition(x, y, [EasyStar.TOP, EasyStar.LEFT]): Restricts access to a tile to specific directions.
    • Cost and Obstacles:

      • setTileCost(tileType, multiplicativeCost): Adjusts the cost of moving through specific tile types.
      • setAdditionalPointCost(x, y, cost): Sets a specific cost for a single coordinate.
      • avoidAdditionalPoint(x, y): Treats a specific coordinate as an obstacle.
    • Performance and Execution:

      • setIterationsPerCalculation(someValue): Limits the number of iterations per calculate() call to prevent frame drops.
      • enableSync(): Switches from asynchronous to synchronous calculation.
      • cancelPath(instanceId): Cancels a pathfinding request using the ID returned by findPath.
  8. Avoid specific points

    master

    Force the pathfinder to avoid specific coordinates, even if they are marked as acceptable tiles.

    • avoidAdditionalPoint(x, y): Marks a coordinate as an obstacle.
    • stopAvoidingAdditionalPoint(x, y): Removes the avoidance rule for a coordinate.
    • stopAvoidingAllAdditionalPoints(): Clears all avoidance rules.
  9. Set directional conditions on tiles

    master

    You can restrict movement into or out of specific tiles by defining allowed directions. Use the constants exported by EasyStar to specify directions.

    • setDirectionalCondition(x, y, allowedDirections): Takes an array of direction strings (e.g., ['TOP', 'BOTTOM']).
    • removeAllDirectionalConditions(): Clears all directional restrictions.
  10. Avoid specific points on the grid

    master

    If you want to prevent the pathfinder from ever stepping on a specific coordinate, regardless of whether that tile is marked as "acceptable," use the avoidance methods.

    • avoidAdditionalPoint(x, y): Adds a point to the avoidance list.
    • stopAvoidingAdditionalPoint(x, y): Removes a point from the avoidance list.
    • stopAvoidingAllAdditionalPoints(): Clears the entire avoidance list.