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

2017/11/4

Timer every 5 seconds something spawns

ZigZagNinja ZigZagNinja

2017/11/4

#
So i want to make a game that requires something (in my case a stone) spawns every five seconds or so (it should also spawn randomly in the map). Is there any possiblity of doing this?? Thanks in advance.
Super_Hippo Super_Hippo

2017/11/4

#
In your active world subclass:
1
2
3
4
5
6
7
8
9
10
private int stoneSpawn=275, stoneSpawnTimer=stoneSpawn;
 
public void act()
{
    if (--stoneSpawnTimer==0)
    {
        stoneSpawnTimer=stoneSpawn;
        addObject(new Stone(), Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight()));
    }
}
ZigZagNinja ZigZagNinja

2017/11/4

#
thanks for the reply but unfortunatly its not working... What am i doing wrong? import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import greenfoot.*; // importiert Actor, World, Greenfoot, GreenfootImage public class GameWorld extends World { private int steinSpawn = 275; private int steinSpawnTimer = steinSpawn; public GameWorld() { super(600, 400, 2); setBackground("grass.jpg"); //neuen Spieler erstellen Spieler neuerSpieler = new Spieler(); //neuen Spieler in die Welt setzen addObject (neuerSpieler, 10, 200); //es wird jede 5 Sekunden ein neuer Stein hinzugefügt steinSpawnTimer = steinSpawnTimer -1; zufälligSteineErstellen(); } //es wird jede 5 Sekunden ein neuer Stein hinzugefügt public void zufälligSteineErstellen() { if (steinSpawnTimer==0) { steinSpawnTimer = steinSpawn; addObject(new Stein(), Greenfoot.getRandomNumber(getWidth()), Greenfoot.getRandomNumber(getHeight())); } } }
Super_Hippo Super_Hippo

2017/11/4

#
Only the act method is called automatically. The constructor is only executed once when the object is created. Add this:
1
2
3
4
public void act()
{
    zufälligSteineErstellen();
}
And in the method, you forgot the -- in the if condition. Remove the two lines in the constructor. Or instead of the --, you add the first line at the beginning of the method. Btw, you don't need to import greenfoot twice.
ZigZagNinja ZigZagNinja

2017/11/4

#
Sorry if im stupid but where should i add that?
Super_Hippo Super_Hippo

2017/11/4

#
Somewhere in the class. (Btw, I just edited the message if you didn't see it yet.)
ZigZagNinja ZigZagNinja

2017/11/4

#
OK thanks you very much it works now
You need to login to post a reply.