UI Heath and ammo bars

From IrrWizard

Jump to: navigation, search

Introduction

This short tutorial shows how you can add a health or ammo bar to your game.


Adding a Health bar

This code will go in the CGamePlayState class as it will be used by all game levels. In the header file add a private variable called m_pHealthBar and a protected function declaration.

CGamePlayState.h

private:
    irr::video::ITexture* m_pHealthBar;
protected:
    void displayHealthBar(CGameManager* pManager, irr::s32 percent);

The health bar needs to be initialised in the Init function:

GamePlayState.cpp

void CGamePlayState::Init(CGameManager* pManager)
{ 
   ...
   // load health bar
   m_pHealthBar =  pManager->getDriver()->getTexture(".media/healthbar.jpg");
   pManager->getDriver()->makeColorKeyTexture(m_pHealthBar,core::position2d<s32>(0,0));
   ...
}

Now we can add the displayHealthBar function to the CGamePlayState class:

//! Display horizontal health bar. Players health as a percentage is shown
//! 100 max health, zero none. Graphic is 256 x 16 pixels
void CGamePlayState::displayHealthBar(CGameManager* pManager, irr::s32 percent)
{
   irr::core::rect< irr::s32 > clip(20, 730, 20 + (256 * percent/100) , 730 + 16); 
   pManager->getDriver()->draw2DImage(m_pHealthBar, irr::core::position2d< irr::s32 >(20,730), 
   irr::core::rect< irr::s32 >(0,0,256,16), &clip, irr::video::SColor(255, 255, 255, 255), true); 
}


Health bar 256 x 16 pixels, programmer art. healthbar.jpg

The screen positioning has been hard coded for ease of demonstration, this ideally should be DEFINED in the header file to allow the image to be displayed correctly if the screen resolution changes.

In the CGamePlayState::Update(pManager) function we can call this passing in the current health of the player as a percentage displayHealthBar(pManager, pManager->getPlayer()->getHealth());You will notice that I've created a Player() class and an getter, (accessor) function on the GameManager (pManager), to get at the players Health. You can add the players health directly to the GameManager for speed, but is far better to create a separate class where all Player related information is stored, (health, strength, level etc.), then have a pointer to this new class on the GameManager with a means to access it, getter & setters.

The GameManager itself shouldn't perform any game specific functionality at all, just marshal or control the general flow, i.e. calling other Managers and interfacing Irrlicht.

Personal tools