Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Spawning enemies around the player

Discussion in '2D' started by joydeb, Dec 27, 2016.

  1. joydeb

    joydeb

    Joined:
    Jun 25, 2016
    Posts:
    1
    In my game I got my player in the center of the screen and I want to spawn enemies from each side of the player.

    In this example enemies only spawn from the top site. I want to spawn enemies from top, left, right and bottom.
    Code (CSharp):
    1. public Vector2 spawnValues;  //x=3, y=6
    2. IEnumerator Enemy1_Spawn()
    3.     {
    4.         while(true){
    5.             for(int i = 0; i < enemy1.count; i++)
    6.             {
    7.                 Vector2 spawnPosition = new Vector2(Random.Range(-spawnValues.x, spawnValues.y),spawnValues.y);
    8.                 Quaternion spawnRotation = Quaternion.identity;
    9.                 Instantiate(enemy1.E1, spawnPosition, spawnRotation);
    10.                 yield return new WaitForSeconds(enemy1.waitTime);
    11.             }
    12.         }
    13.     }
    idk if um thinkin correctly, um beginner. But I just want to spawn enemies from left, right and bottom side like they spawn from the top.
     
  2. Eyeshock

    Eyeshock

    Joined:
    Sep 7, 2012
    Posts:
    60
    Well, there's a lot of ways to do this. Admittedly, I'm not fond of your approach, and I'll explain why in a second, but let's address your example.

    1) Random Spawning Position: For the method you're applying here, you're always going to spawn from above because Y is always 6. If you want to spawn from left and right, Y needs to come closer to 0 and your X needs to always be lower or greater than a number that puts the spawn off screen. So you need more logic rules here, and there are several ways to go about it, but top of my head, you could simply randomly decide direction spawn will come from and use a -x range if left and +x if right OR you could do a -x to +x range and if the spawn exists within a screen range (say -2 and +2) then the x is set to minimum range.

    2) Random Vector of Approach / Set Range of Spawn: you could set a radius of spawn min range of spawn distance, then simply random 1-360 and put your enemy at the min distance in the direction decided by your random number.

    3) Segments: I use this for multiplayer because the random spawning thing creates lots of problems. I divide my play area into a number of screens, and spawns occur from a number of screens away. So 100 units of X = 10 screens, and if I have players in screen 3 and 5, then spawns can only in screen 0-2, 4, 6-9. This is really common in procedural type games.