A* Pathfinding 使用方法

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. 下面是一个鼠标点击地面的操作
using UnityEngine;
using System.Collections.Generic;
using Pathfinding;
public class Test : MonoBehaviour
{
    private Seeker seeker;
    private List < Vector3 > vPath;
    void Awake()
    {
        seeker = GetComponent< Seeker >();
    }
    void Update()
    {
        if ( Input .GetMouseButtonDown(1))
        {
            Ray ray = Camera .main.ScreenPointToRay( Input .mousePosition); // 射线 , 从摄像机到鼠标位置的一条射线
            RaycastHit raycastHit; // 碰撞体信息
            if ( Physics .Raycast(ray, out raycastHit, 81f))
            {
                //raycastHit.point 碰撞到的点
                seeker.StartPath(transform.position,raycastHit.point , OnPathComplete);
            }
        }
        if (vPath!= null && vPath.Count > 1)
        {
            for ( int i = 0; i < vPath.Count; i++)
            {
                int i2 = i + 1;
                if (i2 <= vPath.Count - 1)
                {
                    Debug .DrawLine(vPath[i],vPath[i2], Color .green);
                }
            }
        }
    }
    void OnPathComplete( Path p)
    {
        if (!p.error)
        {
            ABPath abPath = p as ABPath ;
            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、付费专栏及课程。

余额充值