- Home /
Question by
UniluckStudios · Nov 11, 2017 at 03:56 PM ·
instantiaterandomphysics2doverlapsphererandomspawning
Physic2D.overlapCircle Instantiation
In my game, I am spawning spikes at a random point in an area on the y axis. The problem is that I don't know how to make the spikes not get instantiated on top of one another. I have looked into using Physics2D.overlapCircle, but idk how to implement it. If there are any other means for doing this, please tell me. Here is my spawning code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnSpikes : MonoBehaviour
{
Vector2 cameraPos;
public GameObject twoSpikes;
public GameObject twoSpikesLeft;
private Vector2 screenSize;
Vector2 spawnPositions;
Vector2 spawnPositionLeft;
Vector2 yValue;
Vector2 xValue;
Vector2 maxY;
void Start()
{
cameraPos = Camera.main.transform.position;
xValue.x = cameraPos.x + screenSize.x;
screenSize.x = Vector2.Distance(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)), Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0))) * 0.5f;
screenSize.y = Vector2.Distance(Camera.main.ScreenToWorldPoint(new Vector2(0, 0)), Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height))) * 0.5f;
Debug.Log(spawnPositions);
InvokeRepeating("spawnTwoSpike", 1.0f, 0.4f);
}
private void spawnTwoSpike ()
{
Instantiate(twoSpikes, spawnPositions, Quaternion.identity);
Instantiate(twoSpikesLeft, spawnPositionLeft, Quaternion.identity);
}
private void FixedUpdate()
{
cameraPos = Camera.main.transform.position;
yValue.y = cameraPos.y + screenSize.y;
maxY.y = yValue.y + 10;
spawnPositions = new Vector2(xValue.x + (screenSize.x * 2) * 0.5f, Random.Range(yValue.y + (screenSize.y * 2) * .5f, (yValue.y + (screenSize.y * 2) * .5f) + 10));
spawnPositionLeft = new Vector2(xValue.x - (screenSize.x * 2) * 0.5f, Random.Range(yValue.y + (screenSize.y * 2) * .5f, (yValue.y + (screenSize.y * 2) * .5f) + 10));
Debug.Log(spawnPositions);
}
}
Comment