Can someone help me create an energy bar for a game that gets higher when clicked

Hi guys! I’ve been trying to teach myself coding and I wanted to try to make an energy bar that goes up when its clicked instead of just immediately displaying the entire energy bar. This is the code I have so far. The clicking works but it still has a starting position where the whole bar is displayed. Can someone help me complete it?

float energy = 100;
float MAX_ENERGY = 100;
float barWidth = 200;
float barHeight = 30;
float x, y;

void setup()
{
size(800, 600);
}

void draw()
{
background(0);

if (energy < 25)
{
fill(#FFB515);
} else if (energy < 50)
{
fill(#FFCD00);
} else
{
fill(#FBFF2C);
}

noStroke();

x = 50;
y = height/4 * 3;
float energyWidth = (energy / MAX_ENERGY) * barWidth;
rect(x, y, energyWidth, barHeight);

stroke(255);
noFill();
rect(x, y, barWidth, barHeight);
}

void mousePressed()
{
if (energy > 0 && mouseButton == RIGHT)
{
energy -= 10;
}
if (energy < 100 && mouseButton == LEFT)
{
energy += 10;
}
}

float energy = 10;
float energyCount = 0;

float MAX_ENERGY = 100;
float barWidth = 200;
float barHeight = 30;
float x, y;

void setup()
{
  size(800, 600);
}

void draw()
{
  background(0);

  if (energy < 25)
  {
    fill(#FFB515);
  } else if (energy < 50)
  {
    fill(#FFCD00);
  } else
  {
    fill(#FBFF2C);
  }

  noStroke();

  x = 50;
  y = height/4 * 3;
  float energyWidth = (energyCount / MAX_ENERGY) * barWidth;
  rect(x+1, y+1, energyWidth-1, barHeight-1);

  stroke(255);
  noFill();
  rect(x, y, barWidth, barHeight);

  energyCount+=.2;
  if (energyCount>=energy)
    energyCount=energy;
}

void mousePressed()
{
  if (energy > 0 && mouseButton == RIGHT)
  {
    energy -= 10;
  }
  if (energy < 100 && mouseButton == LEFT)
  {
    energy += 10;
    // energyCount=0;
  }
}

thanks! Do you think you can explain a little of what you’re doing? I wanna learn from my mistakes and struggles.

Sure

Core idea was

float energyCount = 0;

I increment energyCount slowly until it reaches energy

when displaying the bar, I use energyCount

  float energyWidth = (energyCount / MAX_ENERGY) * barWidth;

Chrisir

1 Like