1

So im building a small Bulletgell game, and im at the point where I want Enemys to spawn in at random Spawnpoints in a given area. I did that with help of the BoxCollider2D, everything works fine but I want them to spawn OUTSIDE the actuall Map so they need to walk in the Map and Screen where the Player is. I just can spawn them in the whole are of the BoxCollider. Is there a way to determine which area the SpawnScript can use ?

In the Picture the red marked area should be the area where the Enemy spawn randomly.

Thanks for the help:)enter image description here

Heres the code im using atm:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class box : MonoBehaviour
{
public GameObject spawnedPrefab;
public BoxCollider2D spawnArea;
Vector2 maxSpawnPos;

float lastSpawnTimeS = -1;
public float spawnDelayS = 5;

// Use this for initialization
void Start()
{
    spawnArea = GetComponent<BoxCollider2D>();
    spawnArea.enabled = false; 
    maxSpawnPos = new Vector2(spawnArea.size.x / 2, spawnArea.size.y / 2);
}

// Update is called once per frame
void Update()
{
    if (lastSpawnTimeS < 0)
    {
        lastSpawnTimeS = Time.time;
        GameObject spawned = Instantiate(spawnedPrefab, Vector3.zero, Quaternion.identity) as GameObject;
        spawned.transform.parent = transform;
        Vector3 pos = new Vector3(Random.Range(-maxSpawnPos.x, maxSpawnPos.x), Random.Range(-maxSpawnPos.y, maxSpawnPos.y), 0);
        spawned.transform.localPosition = pos;
    }
    else if (lastSpawnTimeS >= 0 && Time.time - lastSpawnTimeS > spawnDelayS)
    {
        lastSpawnTimeS = -1;
    }
}

}

Progman
  • 16,827
  • 6
  • 33
  • 48
Dimosaurier
  • 21
  • 1
  • 2

1 Answers1

0

If object tries to go outside spawn area it will reset it to zero. You can also place if condition if object placed at zero add some random position within area.

if (lastSpawnTimeS < 0)
{
    lastSpawnTimeS = Time.time;
    GameObject spawned = Instantiate(spawnedPrefab, Vector3.zero, Quaternion.identity) as GameObject;
    spawned.transform.parent = transform;
    Vector3 pos = new Vector3(Random.Range(-maxSpawnPos.x, maxSpawnPos.x) % spawnArea.size.x, Random.Range(-maxSpawnPos.y, maxSpawnPos.y) % spawnArea.size.y, 0);
    spawned.transform.localPosition = pos;
}
else if (lastSpawnTimeS >= 0 && Time.time - lastSpawnTimeS > spawnDelayS)
{
    lastSpawnTimeS = -1;
}
Syed Mohib Uddin
  • 718
  • 7
  • 16