Stefan
Stefan

Reputation: 113

Timer in java (delay on actions)

so I have this small 2d game I just work on. I'm not that good in java but I do understand alot. But I want to make it so when my character fires a bullet he cant fire anymore for 2 seconds. Or whatever delay. I have tried multiple things but it simply wouldn't work with what I was trying to achieve. This is what I use to fire the bullet.

    if (Mouse.next() && Mouse.isButtonDown(0)) {
        t.scheduleAtFixedRate(task, 0, 10000);
        Game.bullets.add(new Bullet(new Vector2f(position.x + 25, position.y + 19), new Vector2f(position.x, 0)));
    }

Thanks

Upvotes: 1

Views: 518

Answers (1)

Andremoniy
Andremoniy

Reputation: 34900

  1. Create class variable for storing last shot time
  2. Save last shot time in this variable
  3. Compare current time and variable's value on shooting event and decide is it permitted to shot again or not.

Something like:

if (Mouse.next() && Mouse.isButtonDown(0) && (System.currentTimeMillis() - lastShotTime >= 2000)) {
    t.scheduleAtFixedRate(task, 0, 10000);
    Game.bullets.add(new Bullet(new Vector2f(position.x + 25, position.y + 19), new Vector2f(position.x, 0)));
    lastShotTime = System.currentTimeMillis();
}

Upvotes: 1

Related Questions