|
|
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using UnityEngine;
- using UnityEngine.InputSystem;
-
- public class HerdController : MonoBehaviour
- {
-
- [SerializeField]
- private GameObject Prefab;
-
- [SerializeField]
- private int HerdCount = 50;
-
- [SerializeField]
- private Transform SpawnPoint;
-
- [SerializeField]
- private float WaitTime;
-
- [SerializeField]
- private Transform Centre;
-
- private float lastTime;
- private List<PlayerController> Herd;
- private Vector2 recievedInput;
-
- void Start()
- {
- SpawnHerd();
- }
-
- //Recieved movement input from player
- private void OnMovement(InputValue value)
- {
- Vector2 input = value.Get<Vector2>();
- if (input.magnitude > 0)
- input = input.normalized;
-
- Herd.ForEach(p => p.SetMovement(input));
- recievedInput = input;
- }
-
-
- [ContextMenu("Spawn")]
- private void SpawnHerd()
- {
- float radius = 0;
- GameObject prefabExample = Instantiate(Prefab);
- Bounds bound = prefabExample.GetBounds();
- Debug.Log(bound.size);
- Destroy(prefabExample);
-
- if (Herd != null)
- Herd.ForEach(p => Destroy(p));
- Herd = new List<PlayerController>();
-
- for (int i = 0; i < HerdCount; i++)
- {
-
-
-
- int SpawnAttempt = 0;
- while (true)
- {
-
- Vector3 position = Vector3.ProjectOnPlane(Random.onUnitSphere, Vector3.up) * radius;
- Quaternion rotation = Quaternion.identity;
- if (SpawnPoint != null)
- position += SpawnPoint.position;
-
- if (SpawnPositionValid(position, rotation, bound))
- {
- GameObject newObject = Instantiate(Prefab, position, rotation, transform);
-
- Herd.Add(newObject.GetComponent<PlayerController>());
-
-
- break;
- }
-
-
- SpawnAttempt++;
- if (SpawnAttempt % 10 == 0)
- {
- radius += bound.size.magnitude;
- }
- if (SpawnAttempt == 100)
- break;
- }
-
-
-
-
- }
- Debug.Log("Total Spawned: " + Herd.Count);
- }
-
- public void FixedUpdate()
- {
- if (recievedInput.magnitude > 0 && lastTime + WaitTime < Time.time)
- {
- Herd.ForEach(p => p.MoveObject(WaitTime));
- lastTime = Time.time;
-
- }
-
- if (Centre != null)
- Centre.position = Herd.Aggregate(new Vector3(0, 0, 0), (s, v) => s + v.transform.position) / (float)Herd.Count;
- }
-
-
- private bool SpawnPositionValid(Vector3 position, Quaternion rotation, Bounds bound)
- {
- Collider[] colliders = Physics.OverlapBox(position, bound.extents, rotation);
-
- Debug.DrawLine(position, position + Vector3.up);
-
- foreach (Collider col in colliders)
- {
- if (col.GetComponentInChildren<PlayerController>())
- return false;
- if (col.GetComponentInParent<PlayerController>())
- return false;
- }
-
- return true;
- }
-
-
-
-
-
-
-
-
- }
|