- Home /
Enemies distance from player
Hi everyone, thanks for giving me attention. So basically I got a simple script to spawn enemies at a certain range around the player, but I don't want them to spawn too close to the player so I tried something like this.
private void Start()
{
InvokeRepeating(nameof(createRandomEnemy), 0.0f, cooldown);
}
void createRandomEnemy()
{
float xRand = Random.Range(0, xLimit);
float zRand = Random.Range(0, zLimit);
Vector3 spawningPos = new Vector3(xRand, 2, -zRand);
if (Vector3.Distance(player.position, spawningPos) < minDistance)
{
Debug.Log("Too close");
return;
}
Instantiate(enemy, spawningPos, Quaternion.identity);
}
what I want this to do is check if the location is too close to the player and if that's the case then just choose another position but when I use return the function doesn't resets (I know that it just breaks the function but IDK what else to use) and it just waits for the cooldown and invokes again, basically skipping the enemy. if any of you got any solutions to this I'd be really happy to see it.
any kind of help is greatly appreciated.
Thanks a lot!
Answer by unity_ek98vnTRplGj8Q · Mar 02, 2020 at 08:55 PM
The easy way is to use a do-while loop that keeps giving you positions until it finds one that works. I've added a count variable so that it does't freeze up if it cant find a good spawn location after a few attempts
void createRandomEnemy () {
Vector3 spawningPos;
int debugCount = 0;
int maxTries = 50;
do{
float xRand = Random.Range (0, xLimit);
float zRand = Random.Range (0, zLimit);
spawningPos = new Vector3 (xRand, 2, -zRand);
debugCount ++;
}
while ((Vector3.Distance (player.position, spawningPos) < minDistance) && debugCount < maxTries);
if(count >= maxTries){
Debug.Log("Could not find a good spawn position after " + debugCount + " attempts.");
return;
}
Instantiate (enemy, spawningPos, Quaternion.identity);
}
There are more efficient ways to do this but honestly this should be fine for your purposes
Thanks a lot for taking your time and helping me out. This works perfectly fine.