Timon de Groot
Timon de Groot

Reputation: 8183

Vertical Healthbar

Right now I'm working on a game and I'm implementing a health bar. I got stuck making the right formula. This is my code of the Hud you see in the image:

public class CharacterHUD {

    private Image image;
    private Player player;

    private float xHealth, yHealth;
    private float healthBarWidth, healthBarHeight;
    private double healthBarY = 0;
    private double multiplier;

    public CharacterHUD(float xHealth, float yHealth, Image image, Player player) {
        this.image = image;
        this.player = player;
        this.xHealth = xHealth; // X Offset from the frame, 20 in this case.
        this.yHealth = yHealth; // Y Offset from the frame, 17 in this case.
        healthBarWidth = 38;
        healthBarHeight = 173;
    }

    public void update(int delta) {
        healthBarY = (yHealth / 100 * player.getHealth());
        multiplier = (yHealth / healthBarY);
        Log.log("Percentage: " + multiplier);
        Log.log("yHealth: " + yHealth + "+ Health: " + healthBarY);
        Log.log("Actual yHealth: " + (healthBarHeight * multiplier));

    }

    public void render(Graphics g) {
        // The coordinates are going from top-left(x,y) to bottomright(width,height). Also, the yHealth is the offset from the frame. 
        Resources.healthBar.draw(xHealth, (float) (healthBarHeight / multiplier) + yHealth, healthBarWidth, (float) (healthBarHeight / multiplier));
        image.draw(0, 0);
    }

}

On 50 health it looks like this:

So

On 75 health it looks like this:

So2

What am I doing wrong?

Upvotes: 2

Views: 572

Answers (2)

John Starich
John Starich

Reputation: 619

Would it be

Resources.healthBar.draw(xHealth, (float) (healthBarHeight / multiplier) - yHealth, healthBarWidth, (float) (healthBarHeight / multiplier));

instead of + yHealth?

Note: I am not familiar with the method you are using but it seems like it is using window coordinates (from the top left) which would mean the y-coordinate to start from should decrease as health increases.

Upvotes: 2

TheOneTrueGod
TheOneTrueGod

Reputation: 11

Your calculation for the height of the bar is backwards. I don't know what order the parameters in that Resource.HealthBar are in or what they allow, but here's some pseudo code for what you want.

topLeft = (healthBarLeft, healthBarTop + (1 - healthPercent) * healthBarHeight)
bottomRight = (healthBarLeft + healthBarWidth, healthBarTop + healthBarHeight)

The (1 - healthPercent) means that when you have 10% health left, the bar will start 90% of the way down.

Edit: If it doesn't support topLeft / bottomRight and instead expects a width / height, use:

dimensions = (healthBarWidth, healthPercent * healthBarHeight)

Upvotes: 1

Related Questions