Hi.
I want to place 4 instances of my Obstacle class in the world at random locations.
When I've tried doing it I only see one object, but I want them at different locations.
How would I go about doing this?
int x = Greenfoot.getRandomNumber(1000);//the width of your world; int y = Greenfoot.getRandomNumber(1000);//the heigth of your world; addObject(new Obstacle(), x, y); addObject(new Obstacle(), x, y); //...
for (int i = 0; i < 4; i++) {
addObject(new Obstacle(), Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
}setImage("Obstacle" + Greenfoot.getRandomNumber(4) + ".png"); public class AnyClass {
public AnyClass() {
//your code you want to put in the constructor;
}
} private void ritem()
{
if (getObjects(Obstacle.class).isEmpty())
{
for (int i = 0; i < 7; i++) {
addObject(new Obstacle(), Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
}
}
if (getObjects(Food.class).isEmpty())
{
for (int i = 0; i < 1; i++) {
addObject(new Food(), Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
}
}
}//in the class you want to add some objects of;
private boolean initialised = false;//you need this because you cant write it in your constructor;
public void act() {
if (!initialised) {
while (!getIntersectingObjects(ClassA.class).isEmpty() || !getIntersectingObjects(CalssB.class).isEmpty()) {// you need to check for every class you don't want this object to intersect with;
setLocation(Greenfoot.getRandomNumber(getWorld().getWidth()), Greenfoot.getRandomNumber(getWorld().getHeight()));
}
initialised = true;
}
}