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

Time:10-19

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

CodePudding user response:

Setup the coordinate system how you want, using transform() and translate(). So:

you want the origin to be at (0, height); bottom left. then you want to flip the Y axis. Example code:

AffineTransform tform = AffineTransform.getTranslateInstance( 0, height);
tform.scale( 1, -1);
g2.setTransform( tform);

CodePudding user response:

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);
}
  • Related