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);
}
}
CodePudding user response:
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();
}