赞
踩
在unityunity游戏开发过程中,敌人、怪物的自动巡逻肯定是无法避免的,今天主要讲 给敌人和怪物设置定点巡逻。
在给怪物、敌人设置顶点巡逻的时候需要引入命名空间using UnityEngine.AI;
- public class Spider : MonoBehaviour {
- private NavMeshAgent agent;//给怪物添加制动巡航组件
- private Animator an;//获取新动画
- public Transform[] waypoints;//创建一个对象数组,把需要导航的位置存入进去
- private int index = 0;
- private float timer = 0;
- private float times = 3;
- private Transform player;
- // Use this for initialization
- void Start () {
- agent = GetComponent<NavMeshAgent>();//
- an = GetComponent<Animator>();
- agent.destination = waypoints[index].position;
- player = GameObject.FindWithTag("Player").transform;
- }
- // Update is called once per frame
- void Update () {
- float dir = Vector3.Distance(player.position, transform.position);//获取玩家距离敌人的距离
- if(dir > 2 && dir < 5)//追踪
- {
- Track();
- }
- else if(dir <= 2)//攻击
- {
- Attack();
- }
- else
- {
- Patrol();
- }
- }
- void Track()
- {
- //transform.LookAt(player.position);//给定条件看向玩家 这行代码可以不用
- agent.SetDestination(player.position);//自动导航到玩家的位置
- }
- void Attack()//攻击
- {
- agent.ResetPath();//停止导航
- transform.LookAt(player.position);
- an.SetTrigger("Attack");
- }
- void Patrol()//自动导航
- {
- if (agent.remainingDistance < 0.5f)//在自动巡航到0.5m后进入这个判断条件
- {
- an.SetInteger("walk",0);
- timer += Time.deltaTime;
- if (timer >= times)
- {
- timer = 0;
- index++;
- index %= 4;//给怪物巡逻几个点位就给几
- agent.SetDestination(waypoints[index].position);//继续网下一个位置导航
- }
- }
- else
- {
- an.SetInteger("walk", 1);//播放动画
- }
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
这里写了怪物自动巡逻,当玩家靠近到一定距离,停止巡逻,走向玩家,叫指定范围,敌人开始攻击玩家。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。