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.alt text

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

For the spawning, after making a random spawning point, do an if statement to see if the position is 0, 0. If it is, do a while statement to keep recreating the coordinates until they both don’t equal 0. I can’t really help with the bouncing off walls unless I see the script you use.

Your picture is missing so hard to say on the second part.

For the first part if you want to change the spawn point you need to set location, not velocity. I assume you meant you want to avoid 0,0 as the velocity? Why not just add a check like:

if(randomX == 0 && randomY == 0) randomX = 1;

It makes your odds of 0,1 slightly higher than other combos, but does that really matter? If so, I’ll post a slightly harder to follow answer.