Search code examples
javagraphics2d

Java Game Dev - How do I create a vertical health bar?


I need some assistance fixing my vertical health bar. It tracks health correctly and updates, but because of how Java draws (from the top left corner, i.e. (0,0)), the bar appears to be upside down. I would like to flip the health bar so it would appear correctly but I am unsure how to do so.

The division in the codes x and y is just to place the bar in the correct position on the canvas. The multiplier is to scale up the health bar to fit a graphical overlay I made for it.

private void drawHealthBar(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.red);
        g2.fillRect(WIDTH - (WIDTH / 50), HEIGHT / 2, 10, ships.get(0).getHealth() * 6);
        
}

Health Bar Example


Solution

  • you need to shift bar depending on amount of health left, like this:

    private void drawHealthBar(Graphics g) {
        final Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.red);
    
        final int w = 10;
        final int h = ships.get(0).getHealth() * 6; // calculate height first
        final int x = WIDTH - (WIDTH / 50);
        final int y = HEIGHT / 2 + (MAX_HEIGHT - h); // shift by height of whitespace
        g2.fillRect(x, y, w, h);
    }