GrassAreaRecorder.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class GrassAreaRecorder : MonoBehaviour
  5. {
  6. public static GrassAreaRecorder ins;
  7. void Awake()
  8. {
  9. ins = this;
  10. init();
  11. }
  12. void OnDestroy()
  13. {
  14. ins = null;
  15. }
  16. void init() {
  17. areaPosList = new AreaInfo[this.transform.childCount];
  18. int i = 0;
  19. foreach (Transform child in this.transform)
  20. {
  21. child.gameObject.SetActive(false);
  22. //顺便记录子物体关键信息
  23. AreaInfo areaInfo = new AreaInfo();
  24. areaInfo.pos = child.transform.position;
  25. areaInfo.radius = child.transform.lossyScale.x / 2;
  26. areaPosList[i] = areaInfo;
  27. i++;
  28. }
  29. }
  30. private struct AreaInfo {
  31. public Vector3 pos;
  32. public float radius;
  33. }
  34. private AreaInfo[] areaPosList;
  35. public bool isInValidArea(Vector3 worldPosition) {
  36. foreach (AreaInfo areaInfo in areaPosList)
  37. {
  38. if (Vector3.Distance(areaInfo.pos, worldPosition) < areaInfo.radius) {
  39. return true;
  40. }
  41. }
  42. return false;
  43. }
  44. public Vector3 randomOneValidAreaPoint() {
  45. return areaPosList[Random.Range(0, areaPosList.Length)].pos;
  46. }
  47. }