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

2018/12/13

Random apperances

dylanriccio8998 dylanriccio8998

2018/12/13

#
How do I make an object randomly appear at any time? Thanks so much.
danpost danpost

2018/12/14

#
dylanriccio8998 wrote...
How do I make an object randomly appear at any time?
I will call the class of the object 'Objekt'. The following will spawn these objects at an average of once every 120 seconds:
// in MyWorld class
public void act()
{
    if(rand(6000) == 0) addObject(new Objekt(), rand(getWidth(), rand(getHeight());
}

public static int rand(int chances)
{
    return Greenfoot.getRandomNumber(chances);
}
If you only want one to spawn -- ever: - if the one added is never removed, use:
if (getObjects(Objekt.class).isEmpty() && rand(6000)) ... 
- if it may be removed, then add a boolean:
private boolean objektSpawned;
and use:
if (!objektSpawned && rand(6000))
{
    objektSpawned = true;
    addObject ...
}
dylanriccio8998 dylanriccio8998

2018/12/14

#
thank you so much
You need to login to post a reply.