U3d_人工智能[一] 之A*寻路算法

1. 主要思想:

 首先,寻路即使寻点,一个一个正确的点走过去,便达成寻路的要求.
 这里,每个点都有3个属性:F,G,H.H是当前点到达终点的预计消耗,可以用距离表示,但是这里我们的计算方法是
/*
*nowend都是点,一个是当前点,一个是终点
*因此,这里计算出来的距离就是两点的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;
    }
    /// <summary>
    /// 更新父节点、g和f、值
    /// </summary>
    /// <param name="parent"></param>
    /// <param name="g"></param>
    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
{

    // Use this for initialization
    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 = 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值