How to randomly place 2D asteroids so they don't overlap with each other?

What is a good way to create 2D asteroids (top to bottom) that don't overlap with each other? If you can provide code in any language like C # or JAVA I would be grateful.


source to share

3 answers

I believe what you are looking for 2D Collision Detection

. Here's a good article on this with a working example code.

EDIT: Based on what you described, if you had every asteroid represented as a Rectangle , then you can just check the intersection:

  • Create an asteroid that is a rectangle.
  • Check the list of existing asteroids to see if it Crosses .
  • If it intersects, go to 1, otherwise add it to the list.

Obviously this is not ideal as overlaps can be allowed, but it would be a pretty quick way to generate what you want (depending on how many asteroids you wanted to place).

EDIT 2: If you want some code that checks for rectangular overlap, it can be found here .



Depends on how complex you are and how you want to make a decision. If you want to place a lot of objects, then repeated and successful testing each time can lead you into an endless loop, if there is no room (pardon the pun) left for another asteroid.

An alternative would be to preserve the data structure of all possible positions left under the asteroid. It will look like a list of places and will start out as a complete list. For example, if you had a simple 3 x 3 grid, the starting list would have 9 locations. Then you pick a random item from the list and use it, and then remove it and any other locations that are now invalidated by this new asteroid. This way you can tell when you have no free space.

Maybe overkill, but interesting problem I was thinking about - good luck!



A simple solution:

for i = 1 to 10
   X = rand();
   Y = rand();
   drawCircle(X,Y, radius);


Complete solution:
You will have to give us more to continue.



All Articles