A* Pathfinding 使用方法

本文详细介绍如何在Unity中利用A*Pathfinding插件进行寻路网格的搭建及角色导航实现。具体步骤包括:设置地面层级、障碍物层级;创建A*节点并配置寻路网格参数;通过代码实现角色对鼠标点击位置的路径寻找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A*Pathfinding使用方法

A*Pathfinding使用方法
  1. 把地面层级设置为Ground ,地面上的障碍物(,房子,墙等)设置为Obstracles
  2. 在场景中创建一个新的游戏对象,命名为"A *",为物体添加AstarPath.cs脚本
  3. AstarPath的面板属性->Grahps->Add New Graph ->选择一个创建地形导航的方式, 选择Grid Graph=方格
  4. AstarPath的面板属性->Grahps->Height testing->Mask->设置为地形层Ground
  5. AstarPath的面板属性->Grahps->Collison testing->Mask->设置为地形上的障碍物层Obstracles
  6. AstarPath的面板属性->About->Show Graphs 打钩,看到导航网格
  7. AstarPath的面板属性->Grahps->Width * Depth, 设置导航网格的宽度和高度,调整为覆盖地形的长度
  8. AstarPath的面板属性->Grahps-> Node Size: 设置导航网格中的方格大小,方格越小精度越高
  9. 设置AstarPath的面板属性->About->Scan钮, 生成网格
 
  1. 角色导航的操作如下:
  2. 为角色添加胶囊碰撞体,添加Seeker.cs脚本
  3. 下面是一个鼠标点击地面的操作
usingUnityEngine;
usingSystem.Collections.Generic;
usingPathfinding;
publicclassTest:MonoBehaviour
{
   privateSeekerseeker;
   privateList<Vector3> vPath;
   voidAwake()
    {
        seeker = GetComponent<Seeker>();
    }
   voidUpdate()
    {
       if(Input.GetMouseButtonDown(1))
        {
           Rayray =Camera.main.ScreenPointToRay(Input.mousePosition);//射线,从摄像机到鼠标位置的一条射线
           RaycastHitraycastHit;//碰撞体信息
           if(Physics.Raycast(ray,outraycastHit, 81f))
            {
               //raycastHit.point碰撞到的点
                seeker.StartPath(transform.position,raycastHit.point , OnPathComplete);
            }
        }
       if(vPath!=null&& vPath.Count > 1)
        {
           for(inti = 0; i < vPath.Count; i++)
            {
               inti2 = i + 1;
               if(i2 <= vPath.Count - 1)
                {
                   Debug.DrawLine(vPath[i],vPath[i2],Color.green);
                }
            }
        }
    }
   voidOnPathComplete(Pathp)
    {
       if(!p.error)
        {
           ABPathabPath = pasABPath;
           if(abPath ==null)
            {
               Debug.Log("This function only handles ABPaths, do not use special path types");
            }
           //Claim the new path
            p.Claim(this);
           // Path couldn't be calculated of some reason.
           // More info in p.errorLog (debug string)
           if(p.error)
            {
                p.Release(this);
               return;
            }
           vPath = abPath.vectorPath;
        }
       else
        {
           Debug.Log("Yay, we got a path back. Did it have an error? " + p.error);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值