Search code examples
javatimedspawning

Need enemyManager to wait between spawning enemies


I have a couple different enemy types and enemyManager arrayList classes for each type. I have each type of enemy randomly spawning at spawn points slightly off screen, coming onto the screen, then off the other side, dying, and randomly responding. The problem is when I use a loop to spawn the objects many of them spawn in the same place or catch up with each other die around the same time and spawn again. I would like to have a delay between them so they are more spread out.

What I am looking for is a way to slow down the looped spawning of enemies in java. I tried extending enemy manager classes by timer and naming the spawn function run but this didn't work.

Also I am not multithreading because I don't really know how to set that up yet and was trying to finish this project without implementing that, but if that seems like the best solution then I guess I will have to.

thanks for any suggestions.

updated .....

class spawnLgCars extends TimerTask {
    public void run() {
        if (lgCars.size() < 10) {
            lgCars.add(new LgCar());
            System.out.println("spawned");
        } else if (lgCars.size() > 10) {
            lgCars.get(0);
        }
    }

}

Here I how I'd like to implement TimerTask, but because it had to be in it's own class it didn't have access to the properties of the instance of lgCars I was using. Then I tried adding extending lgCars by Timer Task and calling the task in the constructor, but this also didn't work. not sure why.


Solution

  • TimerTask and a java.util.Timer won't work because it is not set up to run the repeated code on the Swing event thread and should be avoided with Swing GUI's. Again you should use a Swing Timer since all the code that is called in the Timer's ActionListener is called on the Swing event thread.

    On the other hand, if you have a long running task, such as if you wanted to do image analysis or something else that takes a long time to run, then that should be called in a background thread such as via a SwingWorker.