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

2016/5/8

How to Randomly add actors around edge of world

redteam55 redteam55

2016/5/8

#
Is there a way to randomly add actors at random points along the edges of the world?
danpost danpost

2016/5/9

#
redteam55 wrote...
Is there a way to randomly add actors at random points along the edges of the world?
Actor actor = new EdgeActor();
int x = Greenfoot.getRandomNumber(getWidth()); // random x (possible)
int y = Greenfoot.getRandomNumber(getHeight()); // random y (possible)
if (Greenfoot.getRandomNumber(2) == 0) // which edge to be on
{
    x = (getWidth()-Greenfoot.getRandomNumber(2))%getWidth(); // random edge (left or right)
}
else
{
    y = (getHeight()-Greenfoot.getRandomNumber(2))%getHeight(); // ranom edge (top or bottom)
}
addObject(actor, x, y);
Newbyfungus Newbyfungus

2016/5/9

#
Do you write that code in the world class?
SPower SPower

2016/5/9

#
Yes, in the constructor to be specific.
danpost danpost

2016/5/9

#
Newbyfungus wrote...
Do you write that code in the world class?
The code given was written as if in the world class. Whether it should go in your constructor or not depends on whether you are setting up your world (then, yes, constructor) or you are providing game play behavior (then, act method or a method it calls).
You need to login to post a reply.