Detect when edge of the map is in camera view and dont random spawn enemy inside of it
How do you detect when the edge of the map is in camera view and to not let enemies to spawn from that side inside the wall?
I'm making a 2D shooter game and my edges of the map are just a straight walls made from 4 box colliders.
The map itself is just a square and each side is exactly 168 units away from the center of the map.
Camera is Orthographic and size 18.
Right now I got enemy to spawn in random locations just outside of the camera view at fixed distance, but now I want it to somehow calculate it so that it wouldn't spawn inside an edge of the map (the wall) when it's in my camera view.
Here's the code itself:
void SpawnEnemies()
{
Vector2 randomLocation = default;
Vector2 randomLeft = cam.ViewportToWorldPoint(new Vector2(-0.1f, Random.Range(-0.1f, 1.1f)));
Vector2 randomRight = cam.ViewportToWorldPoint(new Vector2(1.1f, Random.Range(-0.1f, 1.1f)));
Vector2 randomTop = cam.ViewportToWorldPoint(new Vector2(Random.Range(-0.1f, 1.1f), 1.1f));
Vector2 randomBottom = cam.ViewportToWorldPoint(new Vector2(Random.Range(-0.1f, 1.1f), -0.1f));
int i = Random.Range(0, 4);
if (i == 0) { randomLocation = randomLeft; }
if (i == 1) { randomLocation = randomRight; }
if (i == 2) { randomLocation = randomTop; }
if (i == 3) { randomLocation = randomBottom; }
GameObject clone = Instantiate(Enemy, randomLocation, Quaternion.identity);
clone.transform.parent = EnemyObjectParent.transform;
clone.GetComponent<EnemyAI>().SetTransform(playerController.transform);
clone.GetComponent<Enemy>().SetComponent(uiManager, gameManager);
}
Your answer
Follow this Question
Related Questions
Spawn game objects from array to array of transforms 0 Answers
Is there any way to trigger a popUp UI when a player steps in a specific set of tiles? 0 Answers
How do I make the enemies continue spawning? 1 Answer
how create EndLess game Like zombie Tsunami 1 Answer
problim with dontdestroyonload and counts death as 2 0 Answers