1. 主要思想:
首先,寻路即使寻点,一个一个正确的点走过去,便达成寻路的要求.
这里,每个点都有3个属性:F,G,H.H是当前点到达终点的预计消耗,可以用距离表示,但是这里我们的计算方法是
/*
*now和end都是点,一个是当前点,一个是终点
*因此,这里计算出来的距离就是两点的x差和y差的和
*/
H = Mathf.Abs(now.x - end.x) + Mathf.Abs(now.y - end.y);
而G表示的是起点到达当前点的消耗,可以用起点到当前点的距离来表示.但是计算的时候是一个点一个点的加过来,所以G的值在计算过程中可能会改变,因为父节点有可能会改变,我们在算法中是这样计算G的值的:
//now.Parent就是获取到当前点的父节点
G=Vector2.Distance(new Vector2(now.x,now.y),new Vector2(now.Parent.x,now.Parent.y))+now.Parent.G
最后的F=G+H;
2. 创建Point类
此类表示点,也就之最基本的点,寻路时候的一个个的点.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Point{
public Point Parent { get; set; }
public float F { get; set; }
public float G { get; set; }
public float H { get; set; }
public int x { get; set; }
public int y { get; set; }
public bool isWall { get; set; }
public Point(int x, int y, Point parent=null)
{
this.x = x;
this.y = y;
Parent = parent;
isWall = false;
}
public void UpdateParent(Point parent, float g)
{
Parent = parent;
G = g;
F = G + H;
}
}
3. 创建Astar类实现寻路
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AStar : MonoBehaviour
{
void Start()
{
InitMap();
Point start = map[2, 3];
Point end = map[6, 3];
FindPath(start, end);
ShowPath(start, end);
}
private const int mapWith = 15;
private const int mapHeigh = 15;
private Point[,] map =