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

2016/11/8

Spawn Objects every second

Blattstein Blattstein

2016/11/8

#
So I have to do a school project. I want to make my fireballs spawn every second on random coordinates. I followed some instructions on this site but it somehow doesn't work :/ Pls help me i have to finish it today
import greenfoot.*;

/**
 * Write a description of class StartScreen here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class SpielWelt extends World
{
    private int spawnTimer=(Greenfoot.getRandomNumber(3)+1)*60;
    
    /**
     * Constructor for objects of class StartScreen.
     * 
     */
    public SpielWelt()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(1200, 700, 1, false); 
        prepare ();
        runSpawnTimer();
    }
    
    private void prepare ()
    {
        Platform platform = new Platform ();
        addObject (platform, 600, 645);
        
        Spieler spieler = new Spieler ();
        addObject (spieler, 100, 0);

    }
 
    private void runSpawnTimer()
    {
         spawnTimer--;
    if (spawnTimer==0)
    {
        spawn();
        spawnTimer=(Greenfoot.getRandomNumber(3)+1)*60;
    }
    }
    
    private void spawn()
    {
        Fireball fireball = new Fireball();
        addObject (fireball, Greenfoot.getRandomNumber(1200), 0);
    }
}

danpost danpost

2016/11/8

#
You are calling 'runSpawnTimer' from your world constructor. There, it is only executed once, when the world is created (during reset or compilation). If you want it to be executed continuously while the scenario is running, you need to call it from an 'act' method (see the World API documentation).
Blattstein Blattstein

2016/11/8

#
thank you very much, it works now! do you also know how to add multiple fireballs at once? (ike 3-4)
danpost danpost

2016/11/8

#
You could repeat lines 47 and 48 (omitting the 'Fireball' at the beginning of the first line on the repeated lines); or you could enclose those lines in a 'for' loop, the limit of which could be a random value ( maybe '3 + Greenfoot.getRandomNumber(2)' ).
You need to login to post a reply.