Make bots not spawn near player Unity3D

I’m making top down shooter game! Every 3-5second enemies spawn in random positions. I’ve managed this with Random.Range and pixels. But sometimes enemies spawn near the player or at exact position. Is there any way to make bots not spawn near the player? This problem is very critical for my project because if enemy even touches the player, game is over. Here’s my script:

IEnumerator SpawnNext()
    float randX = Random.Range(-8.638889f, 8.638889f);
    float randY = Random.Range(-4.5f, 4.75f);
    GameObject plt = Instantiate(enemy);
    plt.transform.position = new Vector3(randX, randY, 0);
    yield return new WaitForSeconds(1f);

>Solution :

Use a circle-centric random value. In this method, I normalized a random point on a circle and multiplied it by a random distance range. Adding the value to the main player will give the desired result.

var direction = Random.insideUnitCircle.normalized;
var distance = Random.Range(7, 15); // for e.g 7 is min and 15 max
var pos = direction * distance;

GameObject plt = Instantiate(enemy);
plt.transform.position = player.transform.position + new Vector3(pos.x, pos.y);

Leave a Reply