Unity3D实用组件:NavMesh Agent

一、简介

NavMeshAgent components help you to create characters which avoid each other while moving towards their goal. Agents reason about the game world using the NavMesh
and they know how to avoid each other as well as other moving obstacles. Pathfinding and spatial reasoning are handled using the scripting API of the NavMesh Agent.
NavMesh Agent是一个非常好用的角色移动控制组件。它可以通过NavMesh来标记可到达和不可到达的区域。同时它自带寻路和空间推理的脚本,可以控制角色朝着目标移动却不和其他Agent彼此影响,同时它也知道如何避开对方及其他障碍物。

二、NavMesh设置

需要作为障碍物使得Agent无法通过的物体区域需要将其设置为静态(Navigation Static)。这样在后续烘焙过程中才能产生效果。
在这里插入图片描述

三、Inspector面板参数调节

Alt
在Inspector面板中可以对Agent对象的参数进行调整。以下是一些常用的参数及其使用说明。

参数 说明
Speed 运动速度
Angular Speed 旋转速度
Acceleration 加速度
Stopping Distance 停止距离(距目标多远时停止运动)
Quality 品质(高品质的避障会减少Agent的重叠概率,但会有更大计算消耗)
Priority 优先级(在执行回避时,优先级较低的代理将被该代理忽略)

点击Agent Type -> Open Agent Settings后开启以下窗口,在Bake窗口中可以调节Agent检测的高度、半径大小以及可以爬坡的坡度等参数,用以确定Agent的可移动区域。Alt
在调整完后点击Bake对场景进行再次烘焙。

四、示例代码

1.为角色添加代理

//PlayerController.cs
private NavMeshAgent agent; 

2.在Awake中获取组件

//PlayerController.cs
private void Awake()
{
    
    
    agent = GetComponent<NavMeshAgent>();
}

3.移动到目标位置

//PlayerController.cs
	//将agent的移动目标设置为传入的target的位置坐标
    public void MoveToTarget(Vector3 target)
    {
    
    
        agent.isStopped = false;
        agent.destination = target;
    }

其中target可以由鼠标点击的位置来确定,代码实现如下所示:

//MouseManager.cs
    /// <summary>
    /// 点击鼠标控制角色移动
    /// </summary>
    public void MouseController()
    {
    
    
        if (Input.GetMouseButtonDown(0) && hitInfo.collider!=null)
        {
    
    
            switch(hitInfo.collider.gameObject.tag)
            {
    
    
                case "Ground":
                    EventHandler.CallMouseClickedEvent(hitInfo.point);
                    break;
            }
        }
    }

在这里需要为移动区域添加Ground标签

在代码中使用了事务代理,注册MouseClickedEvent并在PlayerController.cs中进行实现。

//EventHandler.cs
    /// <summary>
    /// 鼠标点击相应事件
    /// </summary>
    public static event Action<Vector3> MouseClickedEvent;

    public static void CallMouseClickedEvent(Vector3 target)
    {
    
    
        MouseClickedEvent?.Invoke(target);
    }

注册事件

//PlayerController.cs
    private void OnEnable()
    {
    
    
        EventHandler.MouseClickedEvent += OnMouseClickedEvent;
    }

    private void OnDisable()
    {
    
    
        EventHandler.MouseClickedEvent -= OnMouseClickedEvent;
    }
//PlayerController.cs
    private void OnMouseClickedEvent(Vector3 target)
    {
    
    
        MoveToTarget(target);
    }

猜你喜欢

转载自blog.csdn.net/float_freedom/article/details/126179067