0
\$\begingroup\$

I want to know if I am in the right tracks in building a function that gives you 2 secs of rest before you can attack again

int attackRate = 2000;
int timeElapse = 0
public void cooldown() {
      if (timeElapse < attackRate) {
          // do somthing here
          timeElapse++;
        } else {
           timeElapse = 0  
      }

when creating this it doesnt seem to work. am i missing something?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This depends heavily on what is your planned result, what library are you using? \$\endgroup\$ – TomTsagk May 13 '18 at 21:16
2
\$\begingroup\$

No, this has to be called 2000 times to fire. That's way too much. Let's say you call this only once per frame and you run the game at 60 fps. That means this needs around 33.3 seconds to allow the player to attack again. It would be a lot better if you used timestamps:

long lastAttack = 0;
long cooldownTime = 2000; // 2000 milliseconds

public void cooldown() {
    long time = System.currentTimeMillis();
    if (time > lastAttack + coolDownTime) {
        // Do something
        lastAttack = time;
    } 
} 
\$\endgroup\$
1
  • \$\begingroup\$ Yep, I agree with this. I would probably pass in the delta time used by your game loop though. You will probably have multiple cool down timers going at onces.. No need to call time function multiple times per game loop. \$\endgroup\$ – Aholio May 14 '18 at 1:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.