A*寻路算法总结

using UnityEngine;
using System.Collections;

///引用cube
public class ReferenceCube : MonoBehaviour {
    //定义每个格子所对应的坐标
    private int x;
    private int y;
    //构造坐标方法
    public void SetPos(int currentX, int currentY)
    {
        x = currentX;
        y = currentY;
    }
    /// <summary>
    /// 触发检测,判断每个格子所对应的类型:start、end、obstacle、normal
    /// </summary>
    /// <param name="other"></param>
    void OnTriggerEnter(Collider other)
    {
        //若格子触发的是start对象,则为start型
        if (other.tag == CubeTags.startTag)
        {
            AStar.instance.grids[x, y].type = GridType.start;
            //格子的彩色球颜色与start对象一致
            gameObject.GetComponent<MeshRenderer>().material.color = other.GetComponent<MeshRenderer>().material.color;
            //初始坐标为start对象所在的坐标
            AStar.instance.startX = x;
            AStar.instance.startY = y;
            //Debug.Log(AStar.instance.grids[x, y].x + " &" + AStar.instance.grids[x, y].y);
        }
        //若格子触发的是end对象,则为end型
        else if (other.tag == CubeTags.endTag)
        {
            AStar.instance.grids[x, y].type = GridType.end;
            //颜色一致
            gameObject.GetComponent<MeshRenderer>().material.color = other.GetComponent<MeshRenderer>().material.color;
            //结束点坐标与end对象坐标一致
            AStar.instance.endX = x;
            AStar.instance.endY = y;
            //Debug.Log("---------------------------");
            //Debug.Log(AStar.instance.grids[x, y].x + " &" + AStar.instance.grids[x, y].y);
            
        }
        //若格子触发的是obstacle对象,则为obstacle型
        else if (other.tag == CubeTags.obstacle)
        {
            AStar.instance.grids[x, y].type = GridType.obstacle;
            //颜色一致
            gameObject.GetComponent<MeshRenderer>().material.color = other.GetComponent<MeshRenderer>().material.color;
        }
        else
        //若不是以上的三种类型,则为normal型
        {
            AStar.instance.grids[x, y].type = GridType.normal;
        }
    }

 
}

主逻辑

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// 格子类型的枚举
/// </summary>
public enum GridType
{
    start,
    end,
    obstacle,
    normal
}

/// <summary>
/// AStar类,挂在AStar的空物体上
/// </summary>
public class AStar : MonoBehaviour {
    //单例类
    public static AStar instance;
    //引入cube对象
    private GameObject referenceCube;
    //偏移量
    public Vector3 offset;
    //格子的横竖排数量
    private int row = 20;
    private int column = 20;
    //可选格子列表:用于储存每个被选格子周围的上下左右,左上左下右下右上的格子
    private ArrayList canSelectList;
    //被选格子列表:用于储存每次比较之后F值最小的格子
    private ArrayList selectedList;
    //定义一个格子数组(根据每个格子的坐标)
    public Grid[,] grids;
    //定义一个游戏对象数组(根据游戏对象的坐标)
    private GameObject[,] objs;

    //开始位置的坐标
    public int startX;
    public int startY;
    //结束位置的坐标
    public int endX;
    public int endY;
    //用栈来储存selectedList中的值(每次比较之后的F值最小格子)
    private Stack result;
    /// <summary>
    /// 初始化
    /// </summary>
    void Awake()
    {
        referenceCube = Resources.Load<GameObject>("ReferenceCube");
        canSelectList = new ArrayList();
        selectedList = new ArrayList();
        grids = new Grid[20,20];
        objs = new GameObject[20, 20];
        result = new Stack();
    }
    /// <summary>
    /// 实例化20*20格子
    /// </summary>
    void Start()
    {
        instance = this;
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < column; j++)
            {
                grids[i, j] = new Grid(i, j);
                GameObject currentCube = Instantiate(referenceCube, new Vector3(i * 0.5f, 0, j * 0.5f) + offset, Quaternion.identity) as GameObject;
                currentCube.GetComponent<ReferenceCube>().SetPos(i, j);
                objs[i, j] = currentCube;
                
            }
        }
        //开启协程
        StartCoroutine(CountAStar());
        
    }
    /// <summary>
    /// 计算AStar寻路中每个格子的F值,然后做比较,储存在相应的ArrayList中
    /// </summary>
    /// <returns></returns>
    IEnumerator CountAStar()
    {

        yield return new WaitForSeconds(0.3f);
        //将开始点的格子加入到可选列表中
        canSelectList.Add(grids[startX, startY]);
        //作为可选列表的第一个元素
        Grid currentGrid = canSelectList[0] as Grid;
        //若当前的格子不是终点,并且可选格子中有对象,执行下面,否则跳出
        while (currentGrid.type != GridType.end && canSelectList.Count > 0)
        {
            //则定义currentGrid为可选格子列表中的第一个元素
            currentGrid = canSelectList[0] as Grid;
            //若
            if (currentGrid.type == GridType.end)
            {
                Debug.Log("find the path");
                GenerateResult(currentGrid);
            }
            else if (canSelectList.Count == 0)
            {
                Debug.Log("no grid");
            }
            for (int i = -1; i <= 1; i++)
            {
                for (int j = -1; j <= 1; j++)
                {
                    if (i != 0 || j != 0)
                    {
                        int x = currentGrid.x + i;
                        int y = currentGrid.y + j;
                        if(x > 0 && y > 0 && x < row && y < column && !selectedList.Contains(grids[x, y]) &&
                            grids[x, y].type != GridType.obstacle)
                        {
                            //计算g值
                            int g = currentGrid.G + (int)(Mathf.Sqrt(i * i + j * j) * 10);
                            //更新g值
                            if (grids[x,y].G == 0 || g <grids[x,y].G)
                            {
                                grids[x, y].G = g;
                                grids[x, y].parrent = currentGrid;
                            }
                            grids[x, y].H = (int)(Mathf.Abs(endX - x) + Mathf.Abs(endY - y)) * 10;
                            grids[x, y].F = grids[x, y].G + grids[x, y].F;
                            //若不包括在可选arraylis中,加入
                            if (!canSelectList.Contains(grids[x, y]))
                            {
                                canSelectList.Add(grids[x, y]);
                            }
                        }
                    }
                    
                }
            }
            canSelectList.Sort();
            selectedList.Add(currentGrid);
            canSelectList.Remove(currentGrid);
        }
    }

    void GenerateResult(Grid currentGrid)
    {
        if (currentGrid.parrent != null)
        {
            result.Push(currentGrid);
            Debug.Log(currentGrid.x +"/" + currentGrid.y);
            iTween.ColorTo(objs[currentGrid.x, currentGrid.y], Color.blue, 3f);
            GenerateResult(currentGrid.parrent);
        }
    }
}

tag值

using UnityEngine;
using System.Collections;

/// <summary>
/// 场景中的对象所对应的tag值脚本
/// </summary>
public class CubeTags  {

    public static string startTag = "Start";
    public static string endTag = "End";
    public static string obstacle = "Obstacle";
}

格子类

using UnityEngine;
using System.Collections;
using System;

/// <summary>
/// 记录格子的类
/// </summary>
public class Grid:IComparable
{
    //格子所对应的坐标
    public int x;
    public int y;
    //F=G+H,曼哈顿函数所涉及的三个值,其中F=G+H
    //G为该点到起始点的估量代价
    //H为该点到终止点的估量代价
    //F值即为曼哈顿值
    public int F;
    public int G;
    public int H;
    //格子的类型
    public GridType type;
    //格子所对应的父物体
    public Grid parrent;
    //格子的坐标函数
    public Grid(int i, int j)
    {
        x = i;
        y = j;
    }
    /// <summary>
    /// 该类继承一个IComparable接口,可以在该类中自定义一个方法,用于做比较
    /// 如下:比较grid对象的F值的大小,最后按照从小到大的顺序排序
    /// </summary>
    /// <param name="grid"></param>
    /// <returns></returns>
    public int CompareTo(object grid)
    {
        if (this.F > ((Grid)grid).F)
        {
            return 1;
        }
        else if (this.F == ((Grid)grid).F)
        {
            return 0;
        }
        else
        {
            return -1;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,252评论 6 516
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,886评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,814评论 0 361
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,869评论 1 299
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,888评论 6 398
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,475评论 1 312
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 41,010评论 3 422
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,924评论 0 277
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,469评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,552评论 3 342
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,680评论 1 353
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,362评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,037评论 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,519评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,621评论 1 274
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,099评论 3 378
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,691评论 2 361

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,711评论 18 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,664评论 18 399
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,309评论 25 707
  • 前言 在使用Unity开发游戏项目时,经常会遇到一些角色的导航需求,然而Unity提供给我们的NavMesh+Na...
    欣羽馨予阅读 12,400评论 13 58
  • 一、每日必做 看书、听书、学专业课程、英语口语、60s、Lead人物、六级试卷 二、情绪 因为我们讨要说法,走投无...
    小小小grow阅读 202评论 0 0