Animal.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace WildAttack
  5. {
  6. /// <summary>
  7. /// 动物类
  8. /// </summary>
  9. public class Animal : MonoBehaviour
  10. {
  11. #region Members
  12. private Animator anim;
  13. /// <summary>
  14. /// 移动范围
  15. /// </summary>
  16. [SerializeField] private float targetRange;
  17. private Vector3 oriPos;
  18. private Vector3 randomPoint;
  19. [SerializeField] private float idlerestSpawnTime = 0;
  20. #endregion
  21. #region Lifecycle
  22. // Start is called before the first frame update
  23. void Start()
  24. {
  25. anim = GetComponent<Animator>();
  26. oriPos = transform.localPosition;
  27. idlerestSpawnTime = Random.Range(3f, 15f);
  28. GetNewRandomTarget();
  29. }
  30. // Update is called once per frame
  31. void Update()
  32. {
  33. // 判断死亡动画状态
  34. if (anim.GetCurrentAnimatorStateInfo(0).IsName("Dead") && anim.GetCurrentAnimatorStateInfo(0).normalizedTime > 0.9f)
  35. {
  36. Destroy(gameObject);
  37. }
  38. // 随机idle run
  39. float runWeight = Random.Range(0f, 1f);
  40. anim.SetFloat("run", runWeight);
  41. if (Vector3.Distance(transform.position, randomPoint) < 1f)
  42. {
  43. GetNewRandomTarget();
  44. }
  45. else
  46. {
  47. // 判断状态
  48. transform.LookAt(new Vector3(randomPoint.x, transform.position.y, randomPoint.z));
  49. if (anim.GetCurrentAnimatorStateInfo(0).IsName("Run") && idlerestSpawnTime > 0)
  50. {
  51. transform.Translate(Vector3.forward * 5 * Time.deltaTime);
  52. }
  53. }
  54. // idlerest动作3~15秒随机播放一次
  55. if (idlerestSpawnTime <= 0)
  56. {
  57. anim.SetTrigger("idlerest");
  58. idlerestSpawnTime = Random.Range(3f, 15f);
  59. }
  60. else
  61. {
  62. idlerestSpawnTime -= Time.deltaTime;
  63. }
  64. }
  65. #endregion
  66. #region Functions
  67. public void Dead()
  68. {
  69. anim.SetTrigger("dead");
  70. }
  71. /// <summary>
  72. /// 获取新目标点
  73. /// </summary>
  74. void GetNewRandomTarget()
  75. {
  76. float randomX = Random.Range(-targetRange, targetRange);
  77. float randomZ = Random.Range(-targetRange, targetRange);
  78. //会根据角当前位置的一定范围进行随机移动
  79. //Vector3 randomPint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
  80. randomPoint = new Vector3(oriPos.x + randomX, transform.position.y, oriPos.z + randomZ);
  81. }
  82. #endregion
  83. }
  84. }