DogCollisionController.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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)
  35. {
  36. dog.moveToLocation = moveToLocation;
  37. dog.RandomMove();
  38. break;
  39. }
  40. }
  41. }
  42. }
  43. }