Hi everyone!
I’ve just started using Unity this weekend, so my apologies if I’m asking a stupid question!
I’m trying to spawn waves of enemies within an annulus centered around a random player in my scene and between a min and max distance.
The code works well if the player has moved before the 1st wave is spawned, but if the player hasn’t moved, it looks like the minimum distance from the player is ignored, and enemies spawn almost on the player…
Here’s my function to instantiate waves of enemies:
public async void InstantiateEnemyWave(GameObject enemyPrefab, int numberOfEnemies, float minDistanceFromPlayer, float maxDistanceFromPlayer)
{
//Find all players
playerList = Utilities.FindAllPlayers();
//Pick a random player
playerPickedRandomly = playerList[Random.Range(0,playerList.Length-1)];
//Find the x and z coordinates of the player
Vector2 playerPos = new Vector2(playerPickedRandomly.transform.position.x,playerPickedRandomly.transform.position.z);
//Create an annulus centered on the player's position and between a minimum and maximum distance
pointInSpawnArea = Utilities.RandomPointInAnnulus(playerPos,minDistanceFromPlayer,maxDistanceFromPlayer);
//Transform the 2D position on the annulus into a 3D position
spawnPos = new Vector3(pointInSpawnArea.x,1f,pointInSpawnArea.y);
//Instantiate enemies at the spawn position
for (int i = 0; i < numberOfEnemies; i++)
{
//avoid overlap of enemies at spawn
while(Physics.CheckSphere(spawnPos,0.75f))
{
spawnPos.x += Random.Range(-1f,1f);
spawnPos.y = 1f;
spawnPos.z += Random.Range(-1f,1f);
}
PhotonNetwork.InstantiateRoomObject(enemyPrefab.name,spawnPos,Quaternion.identity);
}
}
The function I’m using to create the annulus and return a random point on it is the following:
public static Vector2 RandomPointInAnnulus(Vector2 origin, float minRadius, float maxRadius)
{
var randomDirection = (Random.insideUnitCircle * origin).normalized;
var randomDistance = Random.Range(minRadius, maxRadius);
var point = origin + randomDirection * randomDistance;
return point;
}
Does anyone know what I’m doing wrong?
Thanks!