T H Wright
T H Wright

Reputation: 77

LibGdx How to program an HP Bar?

I am currently trying to program a game using LibGdx. I have a lot of the structure part of my game and I am now seeking to have the game return information to the player. The simplest concept for my UI I can think of are HP bars and ammo counters (for bullets, arrows, etc.). Would this be done through a stage and actors in my GameScreen class? Perhaps in the Rendering class? Or is this a second camera (loaded-in after the background)?

I use a GameScreen class supported by a Map and MapRenderer class to achieve my display.

I will be looking to pick apart the LibGdx tests. Any information to get my feet off the ground would be good!

Upvotes: 3

Views: 3638

Answers (1)

noone
noone

Reputation: 19776

I used this code some time ago (untested for now). It uses just two ninepatches drawn on top of each other. You can use the default skin of libgdx (uiskin from the test resources).

public class HealthBar extends Actor {

    private NinePatchDrawable loadingBarBackground;

    private NinePatchDrawable loadingBar;

    public HealthBar() {
        TextureAtlas skinAtlas = new TextureAtlas(Gdx.files.internal("data/uiskin.atlas"));
        NinePatch loadingBarBackgroundPatch = new NinePatch(skinAtlas.findRegion("default-round"), 5, 5, 4, 4);
        NinePatch loadingBarPatch = new NinePatch(skinAtlas.findRegion("default-round-down"), 5, 5, 4, 4);
        loadingBar = new NinePatchDrawable(loadingBarPatch);
        loadingBarBackground = new NinePatchDrawable(loadingBarBackgroundPatch);
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        float progress = 0.4f;

        loadingBarBackground.draw(batch, getX(), getY(), getWidth() * getScaleX(), getHeight() * getScaleY());
        loadingBar.draw(batch, getX(), getY(), progress * getWidth() * getScaleX(), getHeight() * getScaleY());
    }
}

Keep in mind that you should use an AssetManager to retrieve the atlas texture instead of creating a new Atlas like this.

Upvotes: 6

Related Questions