GameObject overlapping on random spawn
Hi,
I am making a side scrolling game in which I randomly generate positions of mountains and other things and then instantiate the object at the position.
I have spent an entire day trying different methods and searching forums and Google for a solution. Every time it looks like it works and then after a couple of instantiations, there is overlapping again. I am completely confused at why nothing has worked. I have tried renderers with bounds, physics, raycasting, and collision detection. Nothing has worked so far.
Here is the mountain spawning method:
/// <summary>
/// This method spawns mountains to the map only if they are further right than the camera
/// </summary>
void SpawnMountains()
{
//Keep spawning mountains until the maximum number has been reached
while (currentMountains < maxMountains)
{
//Get a position for the mountain so we can use it
GetMountainPosition();
//If that position is already taken, roll again
if (mountainPositions.Contains(mountainPosition))
{
GetMountainPosition();
}
else
{
//Make sure the camera is ahead of the spawn position
if (Camera.main.transform.position.x + 10 < mountainPosition.x)
{
//Create the mountain
Instantiate(mountain, mountainPosition, Quaternion.identity);
}
//Check to make sure there are no overlaps
/*
* I have tried so many different combinations of things
* to get this to work it works for a while and then they overlap
*/
if (Physics.CheckSphere(mountainPosition, 7.5f))
{
Debug.Log("Moving a mountain!");
//Get rid of that mountain to prevent it from causing problems
// overlapping another mountain
Destroy(mountain);
//Roll again
GetMountainPosition();
//Make sure that the camera is still to the right of the position
if (Camera.main.transform.position.x + 10 < mountainPosition.x)
{
Instantiate(mountain, mountainPosition, Quaternion.identity);
}
}
currentMountains++;
//Add the position to the list to prevent a duplicate instantiation
mountainPositions.Add(mountainPosition);
}
}
}
/// <summary>
/// This method gets a random position for a mountain to spawn
/// </summary>
void GetMountainPosition()
{
mountainPosition = new Vector2(Random.Range(0, target.transform.position.x), 3.2f);
}
I know that this code isn't very clean and I'm obviously not doing something correctly, but any help would be appreciated.
Here is a screenshot of what is happening.
Thank you.
Your answer
Follow this Question
Related Questions
How to make sprite follow gameObject on trigger? 0 Answers
Player rotation 2d 0 Answers
Select Object And Spawn it 1 Answer
Random Layout of tiles notworking in 2d game 1 Answer
Sprite Animation via script C# 1 Answer