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

2016/11/17

Need help spawning pigs randomly

cdaawgcodeboi cdaawgcodeboi

2016/11/17

#
I'm trying to make a game similar to space invaders, where pigs spawn at the top of the screen randomly but I cant figure it out. I am pretty new so I really just don't know enough of the language to know what commands to use. any help would be appreciated, thanks
Super_Hippo Super_Hippo

2016/11/17

#
The code to spawn it randomly will look like this:
addObject(new Pig(), Greenfoot.getRandomNumer(getWidth()), 0);
Maybe you want to adjust the 0, maybe you also don't want it to spawn at the edge. Then it could look like this for example:
addObject(new Pig(), Greenfoot.getRandomNumer(getWidth()-20)+20, 10);
If you place that in the act method of your world, your scenario will be full of pigs quite fast. So you will need some sort of requirement to spawn a pig. Maybe after a specific time span or you get a random number and spawn it whenever it is 0 for example.
danpost danpost

2016/11/19

#
Start with a method to spawn a pig (in your World subclass):
private void spawnPig()
{
    Pig pig = new Pig(); // create a pig
    // get dimensions of pig image
    int pWide = pig.getImage().getWidth();
    int pHigh = pig.getImage().getHeight();
    // determine location to place pig in world
    int x = Greenfoot.getRandomNumber(getWidth()-pWide)+pWide/2;
    int y = pHigh/2;
    addObject(pig, x, y); // add pig to world
}
Now, you can call it when needed. For example, if you want to occasionally spawn one and limit the number of pigs in the world to, let us say, ten, then you can have something like this for the world act method:
public void act()
{
    boolean canAddPig= getObjects(Pig.class).size() < 10;
    boolean chanceFavorsAddingPig = Greenfoot.getRandomNumber(125) == 0; 
    if (canAddPig && chanceFavorsAddingPig) spawnPig();
}
You need to login to post a reply.