Uniyt3d 游戏场景中 NPC固定点巡逻 基本实例

场景中有 Capsule,Cube,Plan

给Plane添加组件NavMesh Surface

给Capsule添加组件NavMesh Agent

给Cube添加组件NavMesh Obstacle

在Plane的Inspctor中点击Bake

程序代码如下:

public class BasickPatro : MonoBehaviour
{
    public Transform[] waypoints;
    NavMeshAgent agent;

    private void Awake()
    {
        agent = GetComponent<NavMeshAgent>();
        Debug.Log("the agent is: "+agent);
        agent.destination = waypoints[0].position;
    }
}

将代码挂载给Capsule, 新建一个Empty object,命名为pos1,将其挂载到waypoints里

完成1个目标点的寻路

在以上基础上完成多个点的来回巡逻:

将代码改写为:

using UnityEngine;
using UnityEngine.AI;

public class BasickPatro : MonoBehaviour
{
    public Transform[] waypoints;
    NavMeshAgent agent;
    int index;

    private void Awake()
    {
        agent = GetComponent<NavMeshAgent>();
        //不断向当前位置点前进
        InvokeRepeating("Tick", 0, 0.5f);
        if (waypoints.Length > 0)
        {
            //5秒进入下个位置点
            InvokeRepeating("Patrol", 0, 5f);
        }

    }
    void Patrol()
    {
        //位置点是否到了最后一个,如果是重回第一个位置点,否则到下一个位置点
        index = index == waypoints.Length - 1 ? 0 : index + 1;
    }
    void Tick()
    {
        agent.destination = waypoints[index].position;
    }
}

在场景中添加多个pos点,全部将其挂载到waypoints里,完成多个固定点的巡逻

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值