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

How to make enemies not spawn on/too close to player. C#

I’m making a "player fish eats smaller fish and grows" game as practice. But I’m struggling with making the npc fish not spawn on or too close to the player.
This is the code for the spawner, atm fish can still spawn on the player.

    public class Spawner : MonoBehaviour
{
    public GameObject[] itemsToPickFrom;
    public int numberToSpawn;
    
    float placeX;
    float placeY;

    float minDistance;


    void Start()
    {
        Spawn();
        
        minDistance = 5f;
    }
 
    
  void Spawn()
  {
      for (int i = 0; i < numberToSpawn; i++)
      {
          int randomIndex = Random.Range(0, itemsToPickFrom.Length);
          
          placeX = Random.Range(-10f, 9f);
          placeY = Random.Range(-4f, 4f);

          while (Vector2.Distance(GameObject.FindGameObjectWithTag("Player").transform.position, new Vector3(placeX, placeY, 0)) < minDistance)
          {
              placeX = Random.Range(-10f, 9f);
              placeY = Random.Range(-4f, 4f);
          } 
             
          Instantiate(itemsToPickFrom[randomIndex], new Vector3(placeX, placeY, 0), quaternion.identity);
      }
  }

>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

I guess it’s Unity, if so numberToSpawn is probably set on the editor interface, so it shouldn’t be a problem.

The issue I can see is that you set minDistance after Spawn().

    void Start()
    {
        Spawn();
        
        minDistance = 5f;
    }

If you set minDistance before Spawn(), it could be correct. The other logics seems correct at least.

    float minDistance = 5f;


    void Start()
    {
        Spawn();
    } 
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