71 Astar - JcerelusDev/CanvasGameJs GitHub Wiki
What is Astar algorithm
A* algorithm is a technique used to find the shortest path in a grid . In game pathfinding astar is the suitable algorithm.
Here's a complete example using a json tiled map editor :
function enemyFollow(){
for(let enemy of enemies){
let grid = game.parse2D(data.layers[1]) // used to conver1 1d array into 2d array because the system worjs with 2d array
let endX = Math.floor(player.x / data.tilewidth);
let endY = Math.floor(player.y / data.tileheight);
let startX =Math.floor(enemy.x / 16)
let startY =Math.floor(enemy.y /16)
let astar = new Astar()
astar.setIterations(800)
astar.setGrid(grid)
astar.setAcceptableTiles([0])
astar.setDiagonal(true)
astar.findPath(startX,startY,endX,endY,function(path){
// Check if the path is found
if (path ) {
for(let i = 0; i<path.length; i++){
enemy.path = path
// Move the enemy if the path is available
}
let nextX = enemy.path[1].x * data.tilewidth;
let nextY = enemy.path[1].y * data.tileheight;
let speed = 1
// Move the enemy towards the next point
if (enemy.x < nextX) {
enemy.vx = speed
enemy.x +=enemy.vx ; // Move right
}
if (enemy.x > nextX) {
enemy.vx = - speed
enemy.x +=enemy.vx; // Move left
}
if (enemy.y < nextY) {
enemy.vy = speed
enemy.y += enemy.vy; // Move down
}
if (enemy.y > nextY) {
enemy.vy = - speed
enemy.y += enemy.vy; // Move up
}
}
});
game.avoidSameOverlapping(enemies) // learn about that method later on .
}
}
Here's a short method :
let astar = game.setAstar(16,data.layers[1],[0],900,true)
// 16 is for tileSize
//data.layers[1] is the grid
//[0] is the acceptable tile
// 800 is iteration timer
// true is the dialogmovement enable
you can jump directly in astar.findPath method