为了把A*寻到的路径中一些没必要的节点去掉,可以用到森汉姆算法,如果两点之间经过的节点都是可走的,那就把这两个点连起来,最终拿到的路径就是比较平滑的了。
下面是算法实现:
public
static
function
bresenham(x1:
int
, y1:
int
, x2:
int
, y2:
int
):
Array
{
var
touched:
Array
= [];
var
steep:
Boolean
= Math.abs(y2 - y1) > Math.abs(x2 - x1);
if
(steep)
{
var
tmp:
int
;
tmp = x1;
x1 = y1;
y1 = tmp;
tmp = x2;
x2 = y2;
y2 = tmp;
}
if
(x1 > x2)
{
var
x1_old:
int
= x1;
var
y1_old:
int
= y1;
x1 = x2;
x2 = x1_old;
y1 = y2;
y2 = y1_old;
}
var
deltax:
int
= x2 - x1;
var
deltay:
int
= Math.abs(y2 - y1);
var
error:
int
= deltax /
2
;
var
ystep:
int
;
var
y:
int
= y1;
if
(y1 < y2)
{
ystep =
1
;
}
else
{
ystep = -
1
;
}
for
(
var
x:
int
= x1; x <= x2; ++x)
{
if
(steep)
{
touched.push(
new
Point(y, x));
}
else
{
touched.push(
new
Point(x, y));
}
error = error - deltay;
if
(error <
0
)
{
y = y + ystep;
error = error + deltax;
}
}
return
touched;
}
|
一些资料:http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm