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.5 KiB

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