You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.4 KiB

4 years ago
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.InputSystem;
  6. public class HerdController : MonoBehaviour
  7. {
  8. [SerializeField]
  9. private GameObject Prefab;
  10. [SerializeField]
  11. private int HerdCount = 50;
  12. [SerializeField]
  13. private Transform SpawnPoint;
  14. private List<GameObject> Herd;
  15. //Recieved movement input from player
  16. private void OnMovement(InputValue value)
  17. {
  18. Vector2 input = value.Get<Vector2>();
  19. }
  20. [ContextMenu("Spawn")]
  21. private void SpawnHerd()
  22. {
  23. float radius = 0;
  24. GameObject prefabExample = Instantiate(Prefab);
  25. Bounds bound = prefabExample.GetBounds();
  26. Debug.Log(bound.size);
  27. Destroy(prefabExample);
  28. if (Herd != null)
  29. Herd.ForEach(p => Destroy(p));
  30. Herd = new List<GameObject>();
  31. for (int i = 0; i < HerdCount; i++)
  32. {
  33. int SpawnAttempt = 0;
  34. while (true)
  35. {
  36. Vector3 position = Vector3.ProjectOnPlane(Random.onUnitSphere, Vector3.up) * radius;
  37. Quaternion rotation = Quaternion.Euler(0, Random.Range(-25, 25), 0);
  38. if (SpawnPoint != null)
  39. position += SpawnPoint.position;
  40. if (SpawnPositionValid(position,rotation, bound))
  41. {
  42. GameObject newObject = Instantiate(Prefab, position, rotation, transform);
  43. Herd.Add(newObject);
  44. break;
  45. }
  46. SpawnAttempt++;
  47. if (SpawnAttempt % 10 == 0)
  48. {
  49. radius += bound.size.magnitude;
  50. }
  51. if (SpawnAttempt == 100)
  52. break;
  53. }
  54. Debug.Log("Total Spawned: " + Herd.Count);
  55. }
  56. }
  57. private bool SpawnPositionValid(Vector3 position,Quaternion rotation ,Bounds bound)
  58. {
  59. Collider[] colliders = Physics.OverlapBox(position, bound.extents,rotation);
  60. Debug.DrawLine(position, position + Vector3.up);
  61. foreach(Collider col in colliders)
  62. {
  63. if (col.GetComponentInChildren<PlayerController>())
  64. return false;
  65. if (col.GetComponentInParent<PlayerController>())
  66. return false;
  67. }
  68. return true;
  69. }
  70. }