DogCollisionController.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using UnityEngine;
  2. using UnityEngine.UIElements;
  3. /* 处理Home场景中狗的碰撞检测
  4. * 该脚本用于处理狗与其他物体的碰撞检测
  5. * 通过OnTriggerEnter方法来检测与其他物体的碰撞
  6. * 该脚本需要挂载在狗的GameObject上
  7. */
  8. public class DogCollisionController : MonoBehaviour
  9. {
  10. // Start is called once before the first execution of Update after the MonoBehaviour is created
  11. // void Start()
  12. // {
  13. // }
  14. // // Update is called once per frame
  15. // void Update()
  16. // {
  17. // }
  18. void OnTriggerEnter(Collider other)
  19. {
  20. BoxCollider boxCollider = this.GetComponent<BoxCollider>();
  21. if (boxCollider.isTrigger == true)
  22. {
  23. Debug.Log("collision this" + this.transform.position);
  24. Debug.Log("collision other" + other.transform.position);
  25. Vector3 direction = transform.position - other.transform.position;
  26. Vector3 moveToLocation = this.transform.position + direction.normalized * 0.5f;
  27. if (moveToLocation.x < -5f){moveToLocation.x = -5f;}
  28. if (moveToLocation.x > 5f){moveToLocation.x = 5f;}
  29. if (moveToLocation.z > 5f){moveToLocation.z = 5f;}
  30. Debug.Log("collision moveToLocation" + moveToLocation);
  31. GameObject thisDog = this.gameObject;
  32. foreach (var dog in HomeController.dogsInScene)
  33. {
  34. if (dog.gameObject == thisDog && dog.dogState != DogState.SLEEP)
  35. {
  36. // 如果狗正在睡觉,则不处理碰撞
  37. // 只处理非睡觉状态下的碰撞
  38. Debug.Log("dog move to location" + moveToLocation);
  39. {
  40. dog.moveToLocation = moveToLocation;
  41. dog.RandomMove();
  42. break;
  43. }
  44. }
  45. }
  46. }
  47. }