Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading