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

2012/9/14

Fill an area with actors

jhadad jhadad

2012/9/14

#
Hi, I am making a program in which there is a small actor, and when I call the function I want many of those actors to fill a certain area in the screen, and I have no idea where to start. Any help is greatly appreciated, thanks alot. John
danpost danpost

2012/9/15

#
First I will define an area to put the actors and the number of actors to put there; then, I will create and place that many actors in that area (there are a couple of ways to fill the area, (1) randomly, or (2) evenly; for (2) you will need to get the width and height of the image of the actor and place them next to (and above and below) each other using them (the width and height of the image of the actor) as offsets). The following is for (1) randomly:
// fields for the defining of the area and the number of actors
int leftX = 200, rightX = 400, topY = 100, bottomY = 300;
int totalActors = 100;
// if in a World sub-class, to add the actors in the specified area
for (int i = 0; i < totalActors; i++)
{
    int actorX = leftX + Greenfoot.getRandomNumber(rightX - leftX);
    int actorY = topY + Greenfoot.getRandomNumber(bottomY - topY);
    addObject(new SmallActor(), actorX, actorY);
}
If the code is to be in an Actor sub-class (like a Button or something), just prefix 'addObject(...)' with 'getWorld().'.
jhadad jhadad

2012/9/17

#
Thanks so much, that really helped me out.
You need to login to post a reply.