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

2020/3/23

Spawning objects at random?

whattheheck whattheheck

2020/3/23

#
I have an obstacle class - Obstacle, that I want to contain subclasses of objects that spawn at different times in my project. My code is below: Obstacle class:
public class Obstacle extends Actor
{
    private int spawnTimer;

    public void act() 
    {
        
    }
    void spawning(Actor obs, int interval) {
        spawnTimer = (spawnTimer+1)%interval;
        int randX = Greenfoot.getRandomNumber(getWorld().getWidth());
        int randY = Greenfoot.getRandomNumber(getWorld().getHeight());
        if (spawnTimer == 0)
        {
            getWorld().addObject(obs, randX, randY);
        }
    }
    void removing(Actor obs, int interval) {
        spawnTimer = (spawnTimer+1)%interval;
        if (spawnTimer == 0)
        {
            getWorld().removeObject(obs);
        }
    }
}
Pylon class:
public class Pylon extends Obstacle
{
    public void act() 
    {
        Actor pyl = new Pylon();
        removing(pyl, 300);
        spawning(pyl, 150);
    }    
}
Having the removing and spawning within the pylons act doesn't seem to let them work, and nothing spawns. Using this method also makes it limited so that only one object will appear and disappear randomly. How would I be able to make it so that multiple objects can spawn and disappear after a certain time?
danpost danpost

2020/3/23

#
You cannot spawn objects from inside their class. Well, you can -- but the first must be spawned from outside the class and then they will spawn at an exponential rate that is not wanted. Have your world class randomly spawn the obstacles. The disappearing part can be done in the class of the obstacle.
You need to login to post a reply.