I am currently making a game in Unity 2D, the game is a player in a square arena that has to survive while enemies (green circles) spawn randomly in the arena.
void Start()
{
int randomX = Random.Range(-4, 4);
int randomY = Random.Range(-4, 4);
rigidbody2D.velocity = new Vector2(randomX, randomY);
}
So when the enemies spawn, this code makes them shoot off in a random direction with a random speed. My first question is if there is anyway to keep it from spawning with a vector of (0,0), while very rare, totally possible.
My second, more important question, is that when the enemies are bouncing around sometimes they get stuck in a loop against the walls like in the picture.
That circled enemy was stuck going straight up and down along the wall, although it did not start out like that. How would I go about preventing that from happening? Thanks guys!
Here is my enemy Script:
void Start()
{
int randomX = Random.Range(-4, 4);
int randomY = Random.Range(-4, 4);
rigidbody2D.velocity = new Vector2(randomX, randomY);
}
and it’s spawning code:
IEnumerator Spawn()
{
//Vector3 distanceY = new Vector3(transform.position.y, player.position.y, 0);
yield return new WaitForSeconds(startWait);
for (int i = 0; i < enemyCount; i++)
{
Vector3 spawnLocation = new Vector3(Random.Range(-3, 3), Random.Range(-3, 3), 0);
float distanceX = spawnLocation.x - player.position.x;
float distanceY = spawnLocation.y - player.position.y;
if (Mathf.Abs(distanceX) > 1.5 && Mathf.Abs(distanceY) > 1.5)
{
Instantiate(enemy, spawnLocation, Quaternion.identity);
yield return new WaitForSeconds(spawnWait);
}
else
{
i--;
}
}
}