Java Game Dev: How to put a timer around this code

2020-05-09 22:45发布

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

标签: java timer
2条回答
Animai°情兽
2楼-- · 2020-05-09 23:24

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):

int enemySpawnRate = 3000;
int timeElapsed = enemySpawnRate+1; //Spawn the first time

void spawnEnemy(int delta) {
     timeElapsed +=delta;
     if(timeElapsed>enemySpawnRate) {
       //spawn enemy as before, your code snippet
       timeElapsed=0;
     }
 }

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.

查看更多
放我归山
3楼-- · 2020-05-09 23:34

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 the enemylocation every x ticks. If you tick 60 times per second, that means 3 seconds will be 60 * 3 = 180. That means you can change the enemylocation when tickNumber % 180 == 0

查看更多
登录 后发表回答