0
\$\begingroup\$

Right now I have this:

Thread enemySpawner = new Thread(new Runnable() {
    public void run() {
        if(world.getCurrentState() == gameState.GAME) {
            world.spawnEnemy(x, y);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
});
enemySpawner.start();

It is called in the constructor of my game. For some reason, only one enemy spawns. How do I fix this?

\$\endgroup\$
3
  • \$\begingroup\$ I personally think this is a better way to do it. Mostly because I don't like to sleep threads myself. stackoverflow.com/a/4044793/838023 \$\endgroup\$
    – Chuck D
    Commented Jan 13, 2013 at 4:15
  • 2
    \$\begingroup\$ Why whould you want a thread to spawn enemies? That's too big a cannon for your problem, and you can shoot yourself in the foot.. \$\endgroup\$
    – Liosan
    Commented Jan 13, 2013 at 9:03
  • \$\begingroup\$ Instead of using a thread, just periodically check in your main processing thread whether it's "time to spawn an enemy". This should be in game time, not real time (for example, if someone pauses the game, enemies don't spawn while it's paused) \$\endgroup\$
    – MarkR
    Commented Jan 13, 2013 at 23:04

1 Answer 1

3
\$\begingroup\$

You need to enclose the spawning code in a loop, i.e.

Thread enemySpawner = new Thread(new Runnable() {
    public void run() {
        while(world.getCurrentState() == gameState.GAME) { // Just changed it to a while loop
            world.spawnEnemy(x, y);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
});
enemySpawner.start();

Threads don't run over and over again; you have to implement the loop logic yourself.

\$\endgroup\$
1
  • \$\begingroup\$ Note that the given code does not spawn an enemy every 1 second, because the error of sleeping accuracy is not compensated. You should use Timer instead. \$\endgroup\$
    – msell
    Commented Jan 13, 2013 at 7:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .