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

2014/5/1

Adding multiple objects to the world after an intersection

gamer121 gamer121

2014/5/1

#
Hi, I want to add 10 new food objects into the world randomly every time the Player gets to Home. How do I add the food randomly without copy and pasting the code several times?
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class Home extends Actor
{
    public Home()

    {
        GreenfootImage img = new GreenfootImage(40,40);
        setImage(img);
    }

    public void act()

    {
        Actor player = getOneIntersectingObject(Player.class);  
        if (player != null)  
        {  
            int k = 0;  
            if (getX() == 0) {
                k = 9;
            }
            setLocation(k, k);  
            getWorld().addObject(new Lizard(), Greenfoot.getRandomNumber(10),Greenfoot.getRandomNumber(10));
        } 
    }
}
bourne bourne

2014/5/1

#
Use a loop like the following:
for (int i = 0; i < 10; i++) {
    // Add a food object at random position
}
You need to login to post a reply.