DogCatchDetection.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using TMPro;
  2. using UnityEngine;
  3. public class DogCatchDetection : MonoBehaviour
  4. {
  5. GameObject toy;
  6. GameObject dog;
  7. GameObject dogMouth;
  8. bool isDogRunBack = false;
  9. bool isDogBack = false;
  10. // Start is called once before the first execution of Update after the MonoBehaviour is created
  11. void Start()
  12. {
  13. toy = GameObject.Find("toy");
  14. dog = GameObject.Find("dog");
  15. dogMouth = GameObject.Find("mouth");
  16. }
  17. // Update is called once per frame
  18. void Update()
  19. {
  20. if (isDogRunBack)
  21. {
  22. DogRunBack();
  23. }
  24. if (isDogBack)
  25. {
  26. Animator animator = dog.GetComponent<Animator>();
  27. animator.SetBool("runState", false);
  28. }
  29. }
  30. // 飞盘撞到狗,判断为成功
  31. private void OnTriggerEnter(Collider other)
  32. {
  33. if (other.gameObject.tag == "Throw Material" && other.transform.position.z > -9) // >-9表示丢出一段距离后再检测
  34. {
  35. Debug.Log("狗狗接到飞盘了" + other.gameObject.tag);
  36. PlayData.throwCatched = true;
  37. PlayData.throwEndPosition = other.transform.position; // 提交飞盘停止位置
  38. PlayData.gameStatus = PlayData.GameStatus.finishSuccess;
  39. Debug.Log("toy flied distance:" + PlayData.throwDistance());
  40. // 将玩具碰撞体去掉,并嵌入狗内
  41. Rigidbody rb = toy.GetComponent<Rigidbody>();
  42. rb.isKinematic = true; // 去除重力影响
  43. BoxCollider boxCollider = toy.GetComponent<BoxCollider>();
  44. boxCollider.enabled = false; // 去除碰撞体
  45. toy.transform.SetParent(dogMouth.transform, false);
  46. toy.transform.localPosition = new Vector3(0, 0.1f, 0);
  47. toy.transform.localRotation = Quaternion.Euler(90,0, 0);
  48. toy.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
  49. isDogRunBack = true;
  50. }
  51. }
  52. // 狗狗跑回来
  53. private void DogRunBack()
  54. {
  55. DogProperty dogProperty = EnviromentSetting.puppies[0]; // 读取狗的数据
  56. var basePosition = new Vector3(0, 0.4f, -10.85f);
  57. float dogSpeed = dogProperty.runSpeed / 10; // 狗的移动速度
  58. dog.transform.rotation = Quaternion.RotateTowards(dog.transform.rotation, Quaternion.LookRotation(basePosition), 1080 * Time.deltaTime);
  59. dog.transform.position = Vector3.MoveTowards(dog.transform.position, basePosition, dogSpeed * Time.deltaTime);
  60. if (dog.transform.position == basePosition)
  61. {
  62. isDogBack = true;
  63. }
  64. }
  65. }