How to Instantiate objects at random positions with a certain distance between each other? 2d
Hi,
I have this Spawner script that allows me to instantiate an array of gameobjects (enemies) from a range between two X axis points.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
private float max_X = -5f, min_X = 7f;
public GameObject[] hazards;
private float _timeBtwSpawns;
public float startTimeBtwSpawns;
public float minTimeBetweenSpawns;
public float decrease;
public float minDistance = 30;
public GameObject player;
// Update is called once per frame
void Update()
{
if(player != null)
Spawning();
}
public void Spawning()
{
if (_timeBtwSpawns <= 0)
{
// SPAWN HAZARD
GameObject randomHazard = hazards[Random.Range(0, hazards.Length)];
// Spawn random hazard at random spawn point
float x = Random.Range(min_X, max_X);
Instantiate(randomHazard);
foreach (var hazard in hazards)
{
hazard.transform.position = new Vector2(x, transform.position.y);
}
if (startTimeBtwSpawns > minTimeBetweenSpawns)
{
startTimeBtwSpawns -= decrease;
}
_timeBtwSpawns = startTimeBtwSpawns;
}
else
{
_timeBtwSpawns -= Time.deltaTime;
}
}
}
The problem is as the game goes on, when the enemies start to spawn faster, they start to overlap each other, and it makes the game extremely difficult.
What's the best way to solve this? I'm using c# and it's a 2d game. Thanks, Ejay
Comment