How do I make a bar that shows the progress of a cooldown?

In my game, I currently have 2 weapons. One with a cooldown of 2 seconds, and the other with a cooldown of 4.33 seconds

To make the cooldown, I’m doing:

int time = millis();
boolean fired = false;

if (millis() - time > weaponCooldown * 1000){
    shoot();
    this.fired() = true;
}

The cooldown works really well, but I’m struggling to make a bar that shows the cooldown progress
I’ve managed to make a rectangle that shows up for the cooldown period by doing this:

if (fired() == true){
    fill(255, 255, 255);
    rect(20,20, 100, 10);
}

This is a white bar with a black border, and its the empty bar. I’m trying to make a new black rectangle that will increase in width while the weapon is in cooldown.
How can I do this?

I know I’ll need to do some calculations using the cooldown and bar width (100 pixels), but I just can’t seem to figure out how to do this

I tried using a loop, but since this is in the draw() method, it just gets stuck in the loop

Edit: I want the progress bar to increase from left to right, like a progress bar filling

You have to work with this

Use map () function to go from here to pixels

See reference

progressBarWidth=map( millis() - time,
0, 2000,
0,100);

2 Likes

Use linear interpolation

First take your elapsed time and divide it by the duration of the cooldown. This will give you a value between 0 and 1, you then multiply the full length of the bar with this number to get the length of the progress bar.

Linear interpolation exists in two forms, the “t” or time value represents at which intermediate point in the range you are.

result = (1 - t) * startvalue + t * stopvalue

result = startvalue + (stopvalue - startvalue) * t

If you ponder the formulas for a minute you’ll see it’s quite self-explanatory`

Here’s a useful video:

3 Likes

Does this work if I want the progress bar to always be 100 pixels wide? So if the cooldown is shorter it’ll just take less time to fill up

This should work in that case:

function progressBarWidth(startTime, cooldownDuration, progressBarFullWidth) {
  let currentTime = millis();
  let timeElapsed = currentTime - startTime;
  return map(timeElapsed, 0, cooldownDuration, 0, progressBarFullWidth);
}
3 Likes