简体   繁体   中英

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);
      }
  }

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();
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM