I'm making a "space-invaders style" game. You(the player) move left and right at the bottom of the screen. There will be one enemy in each window, and you have to move to the window and shoot.
I'm working on the enemies popping up system. The window in which an enemy is random and should change every 3 seconds. Here's my code for this:
int enemylocation = new Random().nextInt(2) +1;
if(enemylocation==1){
enemy1.setFilter(Image.FILTER_NEAREST);
enemy1.draw(200,170,s*10);
}
if(enemylocation==2){
enemy2.setFilter(Image.FILTER_NEAREST);
enemy2.draw(200,360,s*10);
}
Everything works, but the random number part is always picking a new number, so both windows are flickering. How can I delay the timer to change the value of enemylocation every 3 seconds and not constantly?
Thanks
I am guessing you already have a gameloop with a timer since you are able to render, the flickering comes from
enemylocation
being set too often so the enemy is rendered all over the place. What I would do is to implement a cooldown. In pseudo-ish code (no IDE):Where delta is the ammount of time that has passed since the previous run of your gameloop.
Note this depends entirely on you have a timerbased gameloop, if you don't and you are rendering on INPUT (eg render if key pressed) the code will be different, you would have to utilize a timertask or a swingtimer if you are using swing.
I'd say the "right" way to do this is to have a game loop that ticks
x
times per second. You decide to change the value of theenemylocation
everyx
ticks. If you tick 60 times per second, that means 3 seconds will be 60 * 3 = 180. That means you can change theenemylocation
whentickNumber % 180 == 0