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

2016/10/16

Spawning Random Actors Problem

abo123 abo123

2016/10/16

#
I spawn 5 Actors randomly on a 7x7 world. How do I avoid that these actors are getting spawned on top of each other. Thanks for your help :)
Super_Hippo Super_Hippo

2016/10/16

#
You could use this in the class which you are spawning:
protected void addedToWorld(World w)
{
    while (isTouching(NameOfTheClass.class))
    {
        setLocation(Greenfoot.getRandomNumber(7), Greenfoot.getRandomNumber(7));
    }
}
abo123 abo123

2016/10/16

#
Thank you yery much, it's working for me. Just one question: Why is there "World w" inside the brackets?
Super_Hippo Super_Hippo

2016/10/16

#
The method is automatically called and it needs a world as a parameter. If you would use any method which usually requires 'getWorld()' in front of it, you can just use 'w' because it is a reference to the world it was added to. But since it is not used, you can change the 'w' to what ever you want.
abo123 abo123

2016/10/16

#
Ok thanks for your time!
You need to login to post a reply.