A星寻路算法先容
你是否在做一款游戏的时间想发明一些怪兽大概游戏主角,让它们移动到一定的地位,避开墙壁和停滞物呢?
假如是的话,请看这篇教程,我们会展现怎样利用A星寻路算法来实现它!
在网上已经有许多篇关于A星寻路算法的文章,但是大部门都是供给应已经相识根本原理的高等开辟者的。
最短的路径是从终点开始,一步步返回到起点构成的(例子:在终点我们可以看到箭头指向右边,所以该方块的前继在它的左边)。
总的来说,我们可以用下面的伪代码,合成猫的寻找过程。这是Objective-C写的,但是你可以用任何的语言去实现它:
[openList add:originalSquare]; // start by adding the original position to the open list
do {
currentSquare = [openList squareWithLowestFScore]; // Get the square with the lowest F score
[closedList add:currentSquare]; // add the current square to the closed list
[openList remove:currentSquare]; // remove it to the open list
if ([closedList contains:destinationSquare]) { // if we added the destination to the closed list, we've found a path
// PATH FOUND
break; // break the loop
}
adjacentSquares = [currentSquare walkableAdjacentSquares]; // Retrieve all its walkable adjacent squares
foreach (aSquare in adjacentSquares) {
if ([closedList contains:aSquare]) { // if this adjacent square is already in the closed list ignore it
continue; // Go to the next adjacent square
}
if (![openList contains:aSquare]) { // if its not in the open list
// compute its score, set the parent
[openList add:aSquare]; // and add it to the open list
} else { // if its already in the open list
// test if using the current G score make the aSquare F score lower, if yes update the parent because it means its a better path
}
}
} while(![openList isEmpty]); // Continue until there is no more available square in the open list (which means there is no path)
版权声明:本文为m0_54851288原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。