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

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;
private List<GameObject> Herd;
//Recieved movement input from player
private void OnMovement(InputValue value)
{
Vector2 input = value.Get<Vector2>();
}
[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<GameObject>();
for (int i = 0; i < HerdCount; i++)
{
int SpawnAttempt = 0;
while (true)
{
Vector3 position = Vector3.ProjectOnPlane(Random.onUnitSphere, Vector3.up) * radius;
Quaternion rotation = Quaternion.Euler(0, Random.Range(-25, 25), 0);
if (SpawnPoint != null)
position += SpawnPoint.position;
if (SpawnPositionValid(position,rotation, bound))
{
GameObject newObject = Instantiate(Prefab, position, rotation, transform);
Herd.Add(newObject);
break;
}
SpawnAttempt++;
if (SpawnAttempt % 10 == 0)
{
radius += bound.size.magnitude;
}
if (SpawnAttempt == 100)
break;
}
Debug.Log("Total Spawned: " + 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;
}
}