A*(Astar)寻路算法的疑惑

问题描述 投票:0回答:0

首先,我是寻路算法的新手。

我正在尝试使用 A* 算法制作一个简单的寻路程序。它可以沿对角线移动并使用欧氏距离来计算启发式(最近路径)。顺便说一句,我正在使用p5.js.

程序完成,看起来可以运行了。但是当我将它与互联网上可用的其他程序进行比较时,我无法得到与您在下面看到的相同的结果:

上图是我做的程序的结果。这是颜色解释:

  • 绿色方块:初始点
  • 黄色方块:目的地
  • 红色方块:从初始点到目标点的最近路径
  • 白色方块:墙壁(不能通过)
  • 蓝色方块:关闭列表(不再使用)

这是代码中最重要的部分:

// Neighbors
let directions = [];
// East
directions[0] = createVector(currentNode.pos.x + 1, currentNode.pos.y);
// West
directions[1] = createVector(currentNode.pos.x - 1, currentNode.pos.y);
// North
directions[2] = createVector(currentNode.pos.x, currentNode.pos.y - 1);
// South
directions[3] = createVector(currentNode.pos.x, currentNode.pos.y + 1);
// Southeast
directions[4] = createVector(currentNode.pos.x + 1, currentNode.pos.y + 1);
// Southwest
directions[5] = createVector(currentNode.pos.x - 1, currentNode.pos.y + 1);
// Northeast
directions[6] = createVector(currentNode.pos.x - 1, currentNode.pos.y + 1);
// Nortwest
directions[7] = createVector(currentNode.pos.x - 1, currentNode.pos.y - 1);

for(let i = 0; i < directions.length; i++) {
  // Is not wall and is not in closed list
  if (isValid(directions[i])) {
    // Cost from initial point
    const g = currentNode.g + 1;
    // Cost till destination point
    const h = euclideanDistance(directions[i]);
    // Make new node based on current square
    const newNode = new Node(currentNode, directions[i], g, h);
    
    // If it is inside open list, get index
    const index = openListContainsNode(newNode);
    if (!index) {
      // If it is not inside open list add it
      openList.push(newNode);
    } else if(index && openList[index].f < newNode.f) { // f is the best estimated cost until destination
      // If there is a better path until destination, remove it from open list and add it again (but this time, with closer parent node)
      openList.push(newNode);
      openList.splice(index, 1);
    }
  }
};

当我在互联网上可用的其他程序上测试结果时,我得到了不同的结果,如下图所示:

来源:https://qiao.github.io/PathFinding.js/visual/

这是我在 p5js 编辑器中可用的代码: https://editor.p5js.org/italoricardogeske/sketches/7H8Q9iIVl

在我的程序中,我在封闭列表(蓝色方块)中有很多漏洞,而在其他程序中没有漏洞。关于导致该问题的原因的任何想法?

javascript path-finding a-star
© www.soinside.com 2019 - 2024. All rights reserved.