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);
UIManager.instance.ChangeBubbleSprite (bubbleClone);
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 colliders's radius is 1.
To create a prefab, you simply have to drag the desired GameObject from your scene hierarchy into the project Assets. Now, to instantiate a GameObject, we call the Instantiate() method in our script.
Instantiate can be used to create new objects at runtime. Examples include objects used for projectiles, or particle systems for explosion effects. Instantiate can also clone script instances directly. The entire game object hierarchy will be cloned and the cloned script instance will be returned.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With