Question

I use easystarjs https://github.com/prettymuchbryce/easystarjs and started with the example on the page.

var grid = [[0,0,1,0,0],
            [0,0,1,0,0],
            [0,0,1,0,0],
            [0,0,1,0,0],
            [0,0,1,0,0]];

//startX, startY ,endX, endY, callback        
easystar.findPath(0, 3, 4, 3, function( path ) {
            path = path || [];
            for(var i = 0, ilen = path.length; i < ilen; i++) {
                //console.log(path[i].x, path[i].y);
                marker.drawRect(path[i].x*32, path[i].y*32, 32, 32);
        }

    });

If I run the code, no way draws out because it is not complete (there is a wall with number one in the road). Is it possible to modify the code so that instead of it just says that the path is not found (or no plots), I want the code to draw the the way as far as possible (to the wall).

The code works if I change one number one to number zero (and create a passage).

Was it helpful?

Solution

The function would return a different result depending on which 1 you turn to 0 so "as far as possible" is relative to that.

Just make it so that if the path is empty you fill it this way:

currentX = startX;
currentY = startY;
path = [];

while(grid[currentY][currentX] != 1){
  path.push({x: currentX, y: currentY});
  dX = endX - currentX;
  dY = endY - currentY;
  distanceX = Math.abs(dX);
  distanceY = Math.abs(dY);
  directionX = dX / distanceX;
  directionY = dY / distanceY;
  // Make a step in the direction where the distance is bigger
  if(distanceX > distanceY){
    currentX += directionX;
  }else{
    currentY += directionY;
  }
}

It'll be a sort of straight line to the destination interrupted by the wall.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top