zoukankan      html  css  js  c++  java
  • unity_小功能实现(敌人巡逻功能)

    利用NavMeshAgent控制敌人巡逻,即敌人在一组位置间循环巡逻。

    首先我们要知道NavMeshAgent中有两个方法:1.锁定当前巡逻的某一目标位置,即navMeshAgent.destination

    2.到达目标位置停止巡逻(休息一定时间继续巡逻),即navMeshAgent.Stop();

    代码实现如下:

    usingUnityEngine;

    usingSystem.Collections;

    using UnityEngine.AI;

    public class EnemyMoveAI : MonoBehaviour {

    public Transform[] directPoints; //0-3

    privateint index = 0;

        public float patroTime = 3f;//到达某一点停止等待时间

        private float timer = 0;//计时器

    privateNavMeshAgentnavMeshAgent;

    void Awake()

        {

    navMeshAgent = GetComponent<NavMeshAgent>();

    navMeshAgent.destination = directPoints[index].position;

        }

    void Update()

        {  

    if (navMeshAgent.remainingDistance< 0.5f)

            {

    timer += Time.deltaTime;

    if (timer==patroTime)

                {

    index++;

                    index %= 4;//在4个点之间循环巡逻

    timer = 0;

    navMeshAgent.destination = directPoints[index].position;

                }

            }

        }

    }

    注意:

    1.为了保证敌人能在该组点内循环巡逻(而不是只巡逻一圈),采用取余的方式获得点数组的下标。

    2.没有使用navMeshAgent.Stop();原因是,如果使用了则到达一个巡逻点后敌人将不会再向新的目标点移动。

  • 相关阅读:
    第四十七课、父子间的冲突
    第四十六课、继承中的构造与析构
    第四十五课、不同的继承方式
    第四十四课、继承中的访问级别
    第四十三课、继承的概念和意义
    第四十二课、类型转换函数(下)
    第四十一课、类型转化构造函数(上)
    暴力大法好
    HideProcess
    Hduacm—5497
  • 原文地址:https://www.cnblogs.com/shirln/p/9105556.html
Copyright © 2011-2022 走看看