当前位置:   article > 正文

unity敌人的巡逻_unity敌人自动巡逻

unity敌人自动巡逻

 在unityunity游戏开发过程中,敌人、怪物的自动巡逻肯定是无法避免的,今天主要讲 给敌人和怪物设置定点巡逻。
在给怪物、敌人设置顶点巡逻的时候需要引入命名空间using UnityEngine.AI;

  1. public class Spider : MonoBehaviour {
  2. private NavMeshAgent agent;//给怪物添加制动巡航组件
  3. private Animator an;//获取新动画
  4. public Transform[] waypoints;//创建一个对象数组,把需要导航的位置存入进去
  5. private int index = 0;
  6. private float timer = 0;
  7. private float times = 3;
  8. private Transform player;
  9. // Use this for initialization
  10. void Start () {
  11. agent = GetComponent<NavMeshAgent>();//
  12. an = GetComponent<Animator>();
  13. agent.destination = waypoints[index].position;
  14. player = GameObject.FindWithTag("Player").transform;
  15. }
  16. // Update is called once per frame
  17. void Update () {
  18. float dir = Vector3.Distance(player.position, transform.position);//获取玩家距离敌人的距离
  19. if(dir > 2 && dir < 5)//追踪
  20. {
  21. Track();
  22. }
  23. else if(dir <= 2)//攻击
  24. {
  25. Attack();
  26. }
  27. else
  28. {
  29. Patrol();
  30. }
  31. }
  32. void Track()
  33. {
  34. //transform.LookAt(player.position);//给定条件看向玩家 这行代码可以不用
  35. agent.SetDestination(player.position);//自动导航到玩家的位置
  36. }
  37. void Attack()//攻击
  38. {
  39. agent.ResetPath();//停止导航
  40. transform.LookAt(player.position);
  41. an.SetTrigger("Attack");
  42. }
  43. void Patrol()//自动导航
  44. {
  45. if (agent.remainingDistance < 0.5f)//在自动巡航到0.5m后进入这个判断条件
  46. {
  47. an.SetInteger("walk",0);
  48. timer += Time.deltaTime;
  49. if (timer >= times)
  50. {
  51. timer = 0;
  52. index++;
  53. index %= 4;//给怪物巡逻几个点位就给几
  54. agent.SetDestination(waypoints[index].position);//继续网下一个位置导航
  55. }
  56. }
  57. else
  58. {
  59. an.SetInteger("walk", 1);//播放动画
  60. }
  61. }
  62. }

这里写了怪物自动巡逻,当玩家靠近到一定距离,停止巡逻,走向玩家,叫指定范围,敌人开始攻击玩家。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/958889
推荐阅读
相关标签
  

闽ICP备14008679号