- Home /
Instantiate prefab randomly but not in already genrated position
I want to generate bubble randomly in my screen.When bubble is generated in one place then other bubble can not generated near of its radius 1 area. means bubbles can not collide or triggered with any other bubbles.
How can i do it ?
public void GenerateBubble ()
{
newBubbleXPos = Random.Range (-7, 7);
newBubbleYPos = Random.Range (-3, 3);
bubbleClone = (GameObject)Instantiate (bubblePrefab, new Vector3 (newBubbleXPos, newBubbleYPos, 0), Quaternion.identity);
bubbleList.Add (bubbleClone);
if (bubblePosList.Contains (bubbleClone.transform.position)) {
bubbleClone.transform.position=new Vector3(Random.Range (-7,7),Random.Range (-3,3),0);
}
bubblePosList.Add (bubbleClone.transform.position);
bubbleClone.transform.parent = UIManager.instance.CurrentLevel.transform;
GLOBALS.bubbleCounter++;
}
In this my code every bubble is generated in different position but it can collide with other bubble means i want to generate new bubble not same position as well as it can not collide also. My bubble collider's radius is 1.
If the bubbles have set positions then you can put all the possible positions in a List and pick from that.
Answer by sudhir_kotila · Mar 10, 2015 at 07:04 AM
I have found Answer :
public List<GameObject> bubbleList = new List<GameObject> ();
private int newBubbleXPos;
private int newBubbleYPos;
public void GenerateBubble ()
{
bool locationInvaild = true;
while (locationInvaild) {
newBubbleXPos = Random.Range (-8, 8);
newBubbleYPos = Random.Range (-4, 4);
currentPosition = new Vector3 (newBubbleXPos, newBubbleYPos, 0);
locationInvaild = false;
for (int i=0; i<bubbleList.Count; i++) {
if (Vector3.Distance (bubbleList [i].transform.position, currentPosition) < 2.5f * radius) {
locationInvaild = true;
break;
}
}
}
bubbleClone = Instantiate (bubblePrefab, new Vector3 (newBubbleXPos, newBubbleYPos, 0), Quaternion.identity) as GameObject;
bubbleList.Add (bubbleClone);
}
Answer by tanoshimi · Aug 06, 2014 at 07:57 AM
Each time you want to generate a new bubble:
Choose a random Vector3 position (using Random.Range)
Call Physics.OverlapSphere to see whether the chosen position touches any colliders.
If no colliders are touched (i.e. OverlapSphere returns false), generate a bubble at this location, otherwise return to 1 and generate a new random location.
Your answer
Follow this Question
Related Questions
How to stop co-routine? 3 Answers
Move Object by dragging (mobile) makes the balls fall from the cup 1 Answer
PhotonNetworking Colliders of players dont collide 0 Answers
Realtime Multiplayer Plugin 2 Answers
Fade in Fade out in unity 1 Answer