Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Spawn enemies randomly, minimum distance from centre of screen

Discussion in 'Scripting' started by LancerStudio, Jul 12, 2019.

  1. LancerStudio

    LancerStudio

    Joined:
    Nov 4, 2016
    Posts:
    2
    I have the following code:

    Code (CSharp):
    1. public class SpawnController : MonoBehaviour
    2. {
    3.  
    4.     public GameObject arrow;
    5.     private float randX, randY;
    6.     Vector2 spawnPosition;
    7.     public float spawnRate = 2f;
    8.     float nextSpawn = 0.0f;
    9.     // Start is called before the first frame update
    10.     void Start()
    11.     {
    12.        
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.         if (Time.time > nextSpawn)
    19.         {
    20.             randX = Random.Range(-70f, 70f);
    21.             randY = Random.Range(-70f, 70f);
    22.             nextSpawn = Time.time + spawnRate;
    23.             spawnPosition = new Vector2(randX, randY);
    24.             Instantiate(arrow, spawnPosition, Quaternion.identity);
    25.         }
    26.     }
    27. }
    This spawns enemies at random positions 70 units from the centre of the screen, I want to implement a minimum distance they can spawn from the centre, i.e. 62 units. So enemies will spawn between 62 units from the centre, and 70 units to the centre, essentially within a circle but outside another circle.

    I can't find any method of doing this so any and all help would be appreciated.
     

    Attached Files:

  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    2,205
    I think:
    Code (csharp):
    1.  
    2. float angle = Random.Range(0, 2f * Mathf.PI);
    3. float range = Random.Range(62, 70);
    4.  
    5. float x = Mathf.Cos(angle) * range;
    6. float y = Mathf.Sin(angle) * range;
    7.  
     
    LancerStudio and StarManta like this.
  3. LancerStudio

    LancerStudio

    Joined:
    Nov 4, 2016
    Posts:
    2
    Many thanks
     
    GroZZleR likes this.