# How do I randomly spawn objects in 2D game?

How do I randomly spawn few different sprites on screen so they're not overlapping or half visible on render. The sprites should immediately start shrinking until they disappear.

I've tried to demonstrate what I have so far using JS, however it's overlapping and not shrinking:

http://jsfiddle.net/SamuraiFox/CVX7D/

Specific to Unity, I've made these sprites prefabs and have put them into the scene from where script would spawn them into game.

• This question deals with a similar problem. Is it helpful? It seems like you have two different problems: One of placing objects and another of making them shrink. These might be better off as different questions.
– Anko
Apr 6 '14 at 11:05

You need a couple of things here -

• Something that will randomly spawn things
• Some way of knowing where sprites already exist so you don't spawn there

It looks like you have a handle on the former so I will cover the latter here.

For unity sprites you have a component called SpriteRenderer from which you can obtain the size of a sprite:

Vector2 size = GetComponent<SpriteRenderer>().bounds.size;


Assuming your pivot is in the top left corner, you can add this size to the transform.position to get the area the sprite takes up.

Rect objectArea = new Rect(transform.position.x, transform.position.y, size.x, size.y);


The Rect object has a handy method called contains. If you keep a list of all the Rects you've made, you could use that, or this method:

public static bool Intersect(this Rect rectA, Rect rectB)
{
return ( Mathf.Abs(rectA.x - rectB.x) < (Mathf.Abs(rectA.width + rectB.width) / 2))
&& (Mathf.Abs(rectA.y - rectB.y) < (Mathf.Abs(rectA.height + rectB.height) / 2));

}


To see if the objects intersect, if they do, try another random position.

Also depending on your use case, look into particle effects (shuriken).

• Thanks for your reply...but while I was waiting for an answer I thought that I could maybe put sprites in a place and than have like 10 objects in static places. Then I would just "spawn" sprites (make them visible and their colliders). I still haven't written a code for it. Would that still be good? I mean I have 30 objects in the scene so there is still a lot of diversity. Apr 8 '14 at 19:52
• Sure, if that works for your use case. :) Apr 8 '14 at 21:31