var Pathfinding = pc.createScript('pathfinding');
// initialize code called once per entity
Pathfinding.prototype.initialize = function() {
this.start = this.entity.getPosition();
this.end = new pc.Vec3(0, 0, 0);
this.path = [];
this.currentWaypoint = 0;
};
// update code called every frame
Pathfinding.prototype.update = function(dt) {
if(this.currentWaypoint >= this.path.length) {
return;
}
var waypoint = this.path[this.currentWaypoint];
var direction = waypoint.sub(this.entity.getPosition());
direction.normalize();
this.entity.translate(direction.scale(dt));
if(waypoint.sub(this.entity.getPosition()).length() < 0.1){
this.currentWaypoint++;
}
};
Pathfinding.prototype.findPath = function(){
// Define a node class for the A* algorithm
class Node {
constructor(x, y, gScore, fScore, parent) {
this.x = x;
this.y = y;
this.gScore = gScore;
this.fScore = fScore;
this.parent = parent;
}
}
// Define a function to get the distance between two nodes
function getDistance(nodeA, nodeB) {
return Math.sqrt((nodeA.x - nodeB.x) ** 2 + (nodeA.y - nodeB.y) ** 2);
}
// Define the A* algorithm function
function AStar(startNode, endNode, grid) {
let openList = [];
let closedList = [];
openList.push(startNode);
while (openList.length > 0) {
// Get the node with the lowest fScore from the openList
let currentNode = openList.reduce((lowestNode, currentNode) => {
if (currentNode.fScore < lowestNode.fScore) {
return currentNode;
} else {
return lowestNode;
}
});
// If we have reached the endNode, return the path
if (currentNode === endNode) {
let path = [];
let node = currentNode;
while (node.parent) {
path.push(node);
node = node.parent;
}
path.push(startNode);
return path.reverse();
}
// Remove the current node from the openList and add it to the closedList
openList.splice(openList.indexOf(currentNode), 1);
closedList.push(currentNode);
// Loop through all the neighbors of the current node
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
// Skip the current node
if (x === 0 && y === 0) {
continue;
}
// Get the coordinates of the neighbor
let neighborX = currentNode.x + x;
let neighborY = currentNode.y + y;
// Skip the neighbor if it is out of bounds
if (neighborX < 0 || neighborX >= grid.length || neighborY < 0 || neighborY >= grid[0].length) {
continue;
}
// Skip the neighbor if it is blocked
if (grid[neighborX][neighborY] === 1) {
continue;
}
// Skip the neighbor if it is in the closedList
let neighborNode = closedList.find((node) => {
return node.x === neighborX && node.y === neighborY;
});
if (neighborNode) {
continue;
}
// Calculate the gScore and fScore of the neighbor
let gScore = currentNode.gScore + getDistance(currentNode, {x: neighborX, y: neighborY});
let fScore = gScore;
};
I just need help with this because I don’t know what’s wrong with it…