Question by
Foldaren · Jul 17, 2020 at 10:57 AM ·
unity 2dspawnpointsborders
Generating object on Camera border,Spawning objects on screen border
Hi. I'm trying to spawn an object on the screen border. I've come up with this code, but I'm sure there must be an easier way to do it. Any help would be appreciated. Here is the code. The static values are generic screen borders, but I will change it later so that It can be dynamically adjusted based on screen ratio and size.
using UnityEngine;
public class MapGeneration : MonoBehaviour
{
float basex, basey, spawnx, spawny, xdist, ydist;
Vector2 basespawn, entryspawn;
public GameObject Base, entrypoint;
int entry = 0;
int entrypointsnum;
// Start is called before the first frame update
void Start()
{
entrypointsnum = Random.Range(2, 5);
basex = Random.Range(-6, 6);
basey = Random.Range(-3, 3);
basespawn = new Vector2(basex, basey);
Instantiate(Base, basespawn, Quaternion.identity);
while(entry != entrypointsnum)
{
spawnx = Random.Range(-8.4f, 8.4f);
spawny = Random.Range(-4.5f, 4.5f);
if (spawnx < 0)
{
xdist = -(-8.4f - spawnx);
}
else if(spawnx > 0)
{
xdist = 8.4f - spawnx;
}
if (spawny < 0)
{
ydist = -(-4.5f - spawny);
}
else if (spawny > 0)
{
ydist = 4.5f - spawny;
}
if(ydist < xdist && spawny > 0)
{
spawny = 4.5f;
}
if (ydist < xdist && spawny < 0)
{
spawny = -4.5f;
}
if (ydist > xdist && spawnx > 0)
{
spawnx = 8.4f;
}
if (ydist > xdist && spawnx < 0)
{
spawnx = -8.4f;
}
entryspawn = new Vector2(spawnx, spawny);
Instantiate(entrypoint, entryspawn, Quaternion.identity);;
entry++;
}
}
Comment
Your answer
Follow this Question
Related Questions
Cinemachine Confiner without IsTrigger? 1 Answer
Shader Graphics not working with Universal Render Pipeline 0 Answers
Physics.OverlapSphere does not detect any 2D Box Colliders! 0 Answers
How to get character from another scene? Character selection game 0 Answers
The object of type 'GameObject' has been destroyed but you are still trying to access it. 0 Answers