Hello SFML'ers!
I just wrote a solution for health bars in my game but not sure if its the best way/correct way to do it?
if it is, then maybe it could be useful for some people!
HealthBar.H
#pragma once
#include <SFML/Graphics.hpp>
class HealthBar
{
public:
HealthBar(void);
~HealthBar(void);
void Draw(sf::Vector2f iPosition, float currentHealth, float maxHealth);
sf::Sprite mCurrentHealth;
sf::Sprite mHealthBackground;
};
HealthBar.cpp
#include "HealthBar.h"
#include "GraphicsManager.h"
HealthBar::HealthBar(void)
{
//load from Graphics
this->mCurrentHealth.setTexture( *Graphics->GetTextureList()[2] );
this->mHealthBackground.setTexture( *Graphics->GetTextureList()[3] );
//Set initial sizes
this->mHealthBackground.setTextureRect( sf::Rect<int>(0, 0, 50, 5) );
this->mCurrentHealth.setTextureRect( sf::Rect<int>(0, 0, 50, 5) );
}
HealthBar::~HealthBar(void)
{
//TODO
}
void HealthBar::Draw(sf::Vector2f iPosition, float currentHealth, float maxHealth)
{
this->mCurrentHealth.setTextureRect( sf::Rect<int>(0, 0, currentHealth / 2, 5));
this->mHealthBackground.setTextureRect( sf::Rect<int>(0, 0, 50, 5) );
this->mCurrentHealth.setPosition(iPosition);
this->mHealthBackground.setPosition(iPosition);
//Draw background first!
Graphics->GetWindow().draw(mHealthBackground);
Graphics->GetWindow().draw(mCurrentHealth);
}
then in my GameEntities I instantiate a healthbar for them each.
each time the GameEntities draw function is called I then also call its healthbar to draw
bar.Draw(this->GetPosition() + sf::Vector2f(-22, -24), health, 100);
resulting in a nice health bar