A* 路算法原理可以参考这个文章,已经写的很详细了http://www.cppblog.com/mythit/archive/2009/04/19/80492.aspx
这篇文章主要写写多人寻路的实时碰撞
先说说无法寻路的情况下,如何移动的离目的地最近的点
其实所有能到达的点都在"关闭列表中",当“开启列表”中所有的点都遍历完后,如果还未找到终点,则视为路径不通
这时候遍历“关闭列表”,找出其中离终点直线距离最短的点即可,见下面代码中findNearPointFromList函数
多人碰撞的大体思路就是
1、用A*找出一条路径
2、按该路径走,没移动一格检测是否发生碰撞
3、如果碰撞,调用A*重新寻路
4、如果未碰撞,按原来路径继续走
5、到目的地停止
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testAstar
{
public class AstarNode
{
private AstarNode parent = null;
private int g;
private int h;
private int x;
private int y;
public AstarNode Parent
{
get
{
return parent;
}
set
{
parent = value;
}
}
public int G
{
get
{
return g;
}
set
{
g = value;
}
}
public int H
{
get
{
return h;
}
set
{
h = value;
}
}
public int F
{
get
{
return g + h;
}
}
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
public int Y
{
get
{
return y;
}
set
{
y = value;
}
}
public AstarNode(int _x, int _y)
{
this.x = _x;
this.y = _y;
this.parent = null;
this.g = 0;
this.h = 0;
}
}
public class Astar
{
private List<AstarNode> openList = new List<AstarNode>();
private List<AstarNode> closeList = new List<AstarNode>();
private bool[,] mapData = null;
private int pixelFormat = 16;
private int mapWidth = 0;
private int mapHeight = 0;
private int endX = 0;
private int endY = 0;
public bool[,] MapData
{
get
{
return mapData;
}
}
public int PixelFormat
{
get
{
return pixelFormat;
}
}
public int MapWidth
{
get
{
return mapWidth;
}
}
public int MapHeight
{
get
{
return mapHeight;
}
}
public Astar()
{
}
private bool isValid(int x, int y)
{
if (x < 0 || x >= mapWidth)
{
return false;
}
if (y < 0 || y >= mapHeight)
{
return false;
}
return true;
}
private bool inList(List<AstarNode> list, int x, int y)
{
foreach (AstarNode node in list)
{
if (node.X == x && node.Y == y)
{