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.
You would have to re-run your thread when it finished, in Android it can be done like this:
First, create your
Runnable
:Then, create a handler, which will be the class that runs the thread (or, well, runnable) and start your
Runnable
like this:This will run every 2 seconds, you could also add a boolean or something simmilar to stop the loop manually.