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\$
  • \$\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 Jan 13 '13 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 Jan 13 '13 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 Jan 13 '13 at 23:04
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\$
  • \$\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 Jan 13 '13 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.