unity中宽度优先算法,实现人物按最短路径移动

定义每个节点的信息

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


public class WayPoint : MonoBehaviour
{
    public bool isExplore;
    public WayPoint exploreForm;//储存父节点
    private void Awake()
    {
        Debug.Log(gameObject.name+"     :   "+GetPoint());
    }

    public Vector2Int GetPoint()//返回 int 类型的 vector 二维向量  物体在世界的坐标
    {
        return new Vector2Int
            (           
               Mathf.RoundToInt(gameObject.transform.position.x),//   Mathf.RoundToInt返回舍入为最近整数的 四舍五入
               Mathf.RoundToInt(gameObject.transform.position.z)
            ) ;     
    }
}
/*mathf. .RoundToInt ()
遇到偶数会返回偶数。
传入11.5f 的结果是 12
传入10.5f 的结果是 10*/


 创建地图并找到最短路径

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using static MapManager;
using static UnityEngine.RuleTile.TilingRuleOutput;

public class MapCreate : MonoBehaviour
{
    [Header("Map Data")]
    public GameObject tilpObject;
    public Vector2 maxSize;
    public UnityEngine.Transform storageParter;

    public Vector2 startPoint;
    public Vector2 endPoint;



    Queue<WayPoint> queue=new Queue<WayPoint>();//储存waypoint类的队列 先进先出
    public Dictionary<Vector2Int,WayPoint> wayPointDict=new Dictionary<Vector2Int, WayPoint>();
    Vector2Int[] directions =
    {
        Vector2Int.up, Vector2Int.down,Vector2Int.left,Vector2Int.right
    };
    public  bool isRunning=true;
    WayPoint searchCenter;
    public static List<WayPoint> pathList= new List<WayPoint>();//起始点到终点的最佳路径

    Vector3 newPos;
   public  GameObject startObject;
   public  GameObject endObject;

    private void Awake()
    {
        GenerateMap();
        LoadAllWayPoint();
        StartFindPath();
    }
    private void StartFindPath()
    {
        BFS();// 宽度优先算法 找到终点
        CreatePath();//根据 终点 反推找到 起始点
    }
    //生成地图  生成初始点 和结束点
    void GenerateMap()
    {
        //生成地图 遍历数组
        for (int i = 0; i < maxSize.x; i++)//行 代表 x
        {
            for (int j = 0; j < maxSize.y; j++)// 列 代表 y
            {
                newPos=new Vector3(-maxSize.x/2-3.5f+3*j, 0, -maxSize.y-3.5f/2+3*i);//0,0为原点生成 居中在镜头中
                var spawnTile = Instantiate(tilpObject, newPos, Quaternion.Euler(0, 0, 0), storageParter);// Quaternion.Euler(0, 0, 0) 旋转0度
                spawnTile.gameObject.name=string.Format("({0}{1})", i, j);
                spawnTile.GetComponentInChildren<TextMeshPro>().text=string.Format("({0}{1})",i,j);
                if(i==startPoint.x&&j==startPoint.y)
                {
                    spawnTile.GetComponent<MeshRenderer>().material.color = Color.blue;
                    spawnTile.GetComponentInChildren<TextMeshPro>().color=Color.blue;
                    startObject= spawnTile;
                }
                if (i==endPoint.x&&j==endPoint.y)
                {
                    spawnTile.GetComponent<MeshRenderer>().material.color = Color.red;
                    spawnTile.GetComponentInChildren<TextMeshPro>().color=Color.red;
                    endObject= spawnTile;
                }

            }
        }
    }
    //遍历每个节点的四邻节点
    void ExploreAround()
    {
        if(isRunning==false) return;
        foreach(Vector2Int diretion in directions)
        {
            var exporeArounds = searchCenter.GetPoint()+diretion*3;//必须*3 应为设置的间隔为3.5  要不然字典没有对于键
            //捕获异常 在容易出错的地方使用 避免游戏出错终止 列如数组超出范围
            try
            {
                var neighbour = wayPointDict[exporeArounds];
                if (neighbour.isExplore==true||queue.Contains(neighbour))//已经被检测 不在运行
                {
                    Debug.Log("捕获异常  以检测");
                }
                else
                {
                    neighbour.exploreForm=searchCenter;
                    queue.Enqueue(neighbour);
                  //  searchCenter.gameObject.GetComponentInChildren<TextMeshPro>().color=Color.black;


                }
            }
            catch
            {
                Debug.Log("异常  ");

            }
        }
    }
//储存所有的 物体的坐标 对于 坐标值
    void LoadAllWayPoint()
    {
        var wayPoints=FindObjectsOfType<WayPoint>();
        foreach(WayPoint wayPoint in wayPoints)
        {
            var tempWayPoint = wayPoint.GetPoint();
            if (wayPointDict.ContainsKey(tempWayPoint))//判断字典中 键是否有对应值 Vector2Int有没有对应的 WayPoint
            {
                Debug.Log("没有字典对于值");
            }
            else
            {
                wayPointDict.Add(tempWayPoint, wayPoint);
                Debug.Log("字典中世界位置"+tempWayPoint);
   
            }
        }        
        Debug.Log("加载全部节点到字典中");
    }

    void BFS()
    {
        Debug.Log("BFS 运行");
        queue.Enqueue(startObject.GetComponent<WayPoint>());
        while(queue.Count > 0&&isRunning)
        {
            Debug.Log("BFS 正在寻找终点");
            searchCenter=queue.Dequeue();//移除节点
             StopIfSearchEnd();//判断是否找到终点
             ExploreAround();
             searchCenter.isExplore= true;
        }
    }
    //找到终点就结束
    void StopIfSearchEnd()
    {
        if(searchCenter==endObject.GetComponent<WayPoint>())
        {
            isRunning= false;
        }
    }
   //反推终点找起始点
    void CreatePath()
    {
        pathList.Add(endObject.GetComponent<WayPoint>());
        WayPoint prePoint = endObject.GetComponent<WayPoint>().exploreForm;
        while(prePoint != startObject.GetComponent<WayPoint>())
        {
            //改变颜色
            prePoint.GetComponent<MeshRenderer>().material.color=Color.yellow;
            pathList.Add(prePoint);
            prePoint= prePoint.exploreForm;
        }
        pathList.Add(startObject.GetComponent<WayPoint>());
        pathList.Reverse();//逆转顺序
    }

    private void Update()
    {
        if(Input.GetKey(KeyCode.Space))
        {
            wayPointDict.Clear();
            queue.Clear();
            pathList.Clear();
            isRunning=true; 
            LoadAllWayPoint();
            StartFindPath();
        }
    }

}

敌人根据地图创建中的路径移动

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

public class EnemyMover : MonoBehaviour
{
    public float waitTime;

    WaitForSeconds waitForSeconds;
    private void Awake()
    {
        waitForSeconds=new WaitForSeconds(waitTime);
    }
    private void Start()
    {
       StartCoroutine(nameof(FindWayPointCorotine));
       //StartCoroutine(FindWayPointCorotine());
    }

    private void Update()
    {
        if(Input.GetKeyUp(KeyCode.Escape))
        {
            StartCoroutine(nameof(FindWayPointCorotine));
        }
    }
    IEnumerator FindWayPointCorotine()
    {

        foreach (var wayPoint in MapCreate.pathList)
        { 
            transform.position = wayPoint.transform.position+new Vector3(0,1,0);
            yield return waitForSeconds;
        }
    }

}

详细看

广度优先搜索算法在Unity网格地图中实现最短路径【解决篇】(含:字典、队列、Vector2Int、List和字符串拼接等问题)_哔哩哔哩_bilibili

分享a*寻路算法的网站

A* 简介 (stanford.edu)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Unity的地图随机算法可以使用Procedural Content Generation(PCG)技术来实现。以下是几种常见的地图随机算法: 1. 随机地形生成:使用随机数生成器和数学函数生成随机地形。可以使用Perlin噪声或Simplex噪声算法来创建连续的高度图,然后根据高度图生成地形特征,例如山脉、河流、湖泊等。 2. 随机物体生成:在地图随机生成物体,例如树木、建筑物或者其他装饰性元素。可以在预定义的区域内随机放置物体,或者使用点、线或面的随机分布算法实现。 3. 关卡布局生成:在关卡随机生成房间、走廊或其他区域,以创建不同的关卡布局。可以使用迷宫生成算法(如深度优先搜索或Prim算法)来生成迷宫式的关卡布局。 4. 随机敌人生成:根据一定的规则和条件,在地图随机生成敌人。可以使用敌人的属性(如难度、类别)和地图的特征(如地形、区域类型)来确定敌人的生成位置和属性。 5. 随机事件生成:在游戏引入随机事件,例如宝箱、陷阱、奖励等。可以使用随机数生成器来决定事件发生的概率,并在合适的位置和时间触发事件。 在实现这些算法时,你可以使用Unity的随机数生成器(如Random类)来生成随机数,并使用Unity的脚本和组件系统来控制地图的生成和布局。同时,你可以使用Unity的工具和资源,如Tilemap系统、Prefab系统和Collision系统,来实现地图的可视化和交互。 记住,地图随机算法的设计需要考虑游戏性、可玩性和性能等因素,以确保生成的地图符合游戏需求并且能够在游戏流畅运行。通过尝试不同的算法和调整参数,你可以逐步优化和改进你的地图随机生成系统。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值