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.

126 lines
2.8 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
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. [SerializeField]
  15. private float WaitTime;
  16. private List<PlayerController> Herd;
  17. void Start()
  18. {
  19. SpawnHerd();
  20. StartCoroutine(MoveRoutine());
  21. }
  22. //Recieved movement input from player
  23. private void OnMovement(InputValue value)
  24. {
  25. Vector2 input = value.Get<Vector2>();
  26. Herd.ForEach(p => p.SetMovement(input));
  27. }
  28. [ContextMenu("Spawn")]
  29. private void SpawnHerd()
  30. {
  31. float radius = 0;
  32. GameObject prefabExample = Instantiate(Prefab);
  33. Bounds bound = prefabExample.GetBounds();
  34. Debug.Log(bound.size);
  35. Destroy(prefabExample);
  36. if (Herd != null)
  37. Herd.ForEach(p => Destroy(p));
  38. Herd = new List<PlayerController>();
  39. for (int i = 0; i < HerdCount; i++)
  40. {
  41. int SpawnAttempt = 0;
  42. while (true)
  43. {
  44. Vector3 position = Vector3.ProjectOnPlane(Random.onUnitSphere, Vector3.up) * radius;
  45. Quaternion rotation = Quaternion.identity;
  46. if (SpawnPoint != null)
  47. position += SpawnPoint.position;
  48. if (SpawnPositionValid(position,rotation, bound))
  49. {
  50. GameObject newObject = Instantiate(Prefab, position, rotation, transform);
  51. Herd.Add(newObject.GetComponent<PlayerController>());
  52. break;
  53. }
  54. SpawnAttempt++;
  55. if (SpawnAttempt % 10 == 0)
  56. {
  57. radius += bound.size.magnitude;
  58. }
  59. if (SpawnAttempt == 100)
  60. break;
  61. }
  62. Debug.Log("Total Spawned: " + Herd.Count);
  63. }
  64. }
  65. public IEnumerator MoveRoutine()
  66. {
  67. foreach (PlayerController pc in Herd)
  68. {
  69. pc.MoveObject();
  70. }
  71. yield return new WaitForSeconds(WaitTime);
  72. StartCoroutine(MoveRoutine());
  73. }
  74. private bool SpawnPositionValid(Vector3 position,Quaternion rotation ,Bounds bound)
  75. {
  76. Collider[] colliders = Physics.OverlapBox(position, bound.extents,rotation);
  77. Debug.DrawLine(position, position + Vector3.up);
  78. foreach(Collider col in colliders)
  79. {
  80. if (col.GetComponentInChildren<PlayerController>())
  81. return false;
  82. if (col.GetComponentInParent<PlayerController>())
  83. return false;
  84. }
  85. return true;
  86. }
  87. }