Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

algorithm to generate random position for game object

I want to generate a position for objects in random manner and i don't want them to overlap with each other . my screen width is 4.8 meter and height is 9.6 meter and the object width is 0.5,and height is 0.5 meter .

can any one put me on the right direction ,or any suggestion .

regards

like image 768
confucius Avatar asked May 25 '26 17:05

confucius


2 Answers

Possible algorithm:

1. Choose random coordinates for all objects.
2. Test for overlap. If it occurs, repeat step 1.

Possible improvements:

1. Reposition overlapping objects with new random coordinates until there is no 
   overlap.
2. Shift any overlapping objects to make them not overlap. Do this intelligently 
   to avoid bunching, if necessary.
like image 177
Michael Goldshteyn Avatar answered May 27 '26 16:05

Michael Goldshteyn


If you can live with your "random" object positions being on a grid, then you can divide the space into 0.5 meter by 0.5 meter squares and pick a square. Your world is 9.6 meters by 4.8 meters. So you have a grid that is 19 x 8.

Put all of the grid positions into a list. For each object that you want to place, randomly pick a grid position from the list and remove it from the list.

If you want to avoid the strict grid appearance, you can alter the x and y positions of your grid centers slightly (add a little here and there). Logically you still have a grid, but the appearance would be less regular.

like image 21
Jim Mischel Avatar answered May 27 '26 17:05

Jim Mischel