This site requires JavaScript, please enable it in your browser!
Greenfoot back
Diphthong
Diphthong wrote ...

2012/11/16

Constructor: Placing randomly Objects, prohibe intersecting

Diphthong Diphthong

2012/11/16

#
Hello to all, I want to place ten Objects randomly in a world. The Objects should not intersect. This is my code:
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(600, 400, 1);
        
for(int i = 0; i < 10; i++)
{
   int x = (Greenfoot.getRandomNumber(560)+20); 
   int y = (Greenfoot.getRandomNumber(360)+20);
        
   while(!getObjectsAt(x, y, bug.class).isEmpty())
   {
       x += 20;
       y += 20;
   }
            
   addObject(new bug(), x, y);
}
It does not work. Often the bugs intersect with other bugs. If I replace the random number generation with a numeral, the bugs does not intersect anymore, but the place is no longer randomly. What is the Problem? Thank you very much! Greetings Diphthong EDIT: This code is in the world class, so I can’t use Actors methods.
danpost danpost

2012/11/16

#
Instead of using a 'while' loop, you can use a 'do-while' loop within the 'for' loop as follows:
for(int i=0; i<10; i++)
{
    bug b = new bug();
    addObject(b, 0, 0);
    do
    {
        int x = 20 + Greenfoot.getRandomNumber(560);
        int y = 20 + Greenfoot.getRandomNumber(360);
        b.setLocation(x, y);
    } while (b.hasIntersectingObject());
}
// add to the bug class the following method
public boolean hasIntersectingObject()
{
    return !getIntersectingObjects(null).isEmpty();
}
Diphthong Diphthong

2012/11/16

#
Thanks, works. :D
You need to login to post a reply.