Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
    
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 –  Rubber Mallet Jan 13 '13 at 4:15
2  
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.. –  Liosan Jan 13 '13 at 9:03
    
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) –  MarkR Jan 13 '13 at 23:04
add comment

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
Thanks! It works! –  dizzydj7 Jan 13 '13 at 3:11
    
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. –  msell Jan 13 '13 at 7:36
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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