How to spawn enemies periodically

1.9k views Asked by At

I am attempting to create a game where enemies will spawn randomly and move towards a point on the screen. My problem is that the program waits for them to spawn and them starts moving them. I want them to start moving as they spawn and have a short break in between each one.

Here's the two main methods behind making them move:

public void newLevel() {
    runOnUiThread(new Runnable(){
        public void run() {
            int i = 0;
            while( i < 10){
                addSpeks();
                i++;
                try {
                    Thread.sleep(2000);
                }
                catch(InterruptedException ie){
                    ie.printStackTrace();
                }
            }
        }
    });
}

public void addSpeks() {
    Spek newSpek = new Spek(this);

    setRandomRegion();

    newSpek.setX(spawnX);
    newSpek.setY(spawnY);

    relativeLayout.addView(newSpek);
    spekList.add(newSpek);
    newSpek.setOnClickListener(spekListener);
    newSpek.animate().x(finalX).y(finalY).setDuration(8000);
}

Spek is a simple class which extends an ImageView and setRandomRegion() selects a random x, y coordinate on the border of the screen. I have a counter in the while loop for simplicity purposes but I would like to eventually move it to a conditional infinite loop where it only stops if you lose the game.

Thanks for any help and let me know if the problem needs more clarification.

2

There are 2 answers

1
Squeazer On BEST ANSWER

You would have to re-run your thread when it finished, in Android it can be done like this:

First, create your Runnable:

private Runnable SpawnEnemies = new Runnable(){
    public void run(){
        //Your code here...

        spawnHandler.postDelayed(2000, this);
    }
};

Then, create a handler, which will be the class that runs the thread (or, well, runnable) and start your Runnable like this:

Handler spawnHandler = new Handler();
spawnHandler.post(new SpawnEnemies());

This will run every 2 seconds, you could also add a boolean or something simmilar to stop the loop manually.

2
Blackbelt On

your newLevel() method runs completely on the UI Thread, and Thread.sleep(2000); is making wait your UI Thread 2seconds each iteration. To add this sort of delay you can use an Handler:

Declare the Handler as member class

final Handler mHandler = new Handler();
int i = 0;

and change newLevel accordingly:

public void newLevel() {
    mHandler.postDelayed(new Runnable(){
        public void run() {
            if (i > 10) {
              mHandler.removeCallbacks(this);
              return;
            }
             addSpeks();
             i++;
             mHandler.postDelayed(this, 2000);                 
        }
    }), 2000);
}

Another optmization would be to declare the Runnable instance as final member, in order to avoid its instationation every time newLevel is called. Check for typo