Based on the tileset from the vertex array tutorial, I have tried to make my own variant for hearts, since i know the tile size and that it will only be one row, I can eliminate some variables.
class health: public sf::Drawable, public sf::Transformable {
public:
int hp;
sf::Texture heartTexture;
sf::VertexArray m_vertices;
void init(void) {
heartTexture.loadFromFile("Heart.png");
hp = 12;
}
void load(void) {
int x = 0;
m_vertices.setPrimitiveType(sf::Quads);
m_vertices.resize(ceil(hp / 4));
//Looping throughout each heart.
for (x = 0; x <= m_vertices.getVertexCount(); x++) {
if (x == m_vertices.getVertexCount()) {
sf::Vertex* quad = &m_vertices[x];
quad[0].position = sf::Vector2f(10 + x * 32, 50);
quad[1].position = sf::Vector2f(10 + ((x + 1) * 32), 50);
quad[2].position = sf::Vector2f(10 + ((x + 1) * 32), 82);
quad[3].position = sf::Vector2f(10 + x * 32, 82);
quad[0].texCoords = sf::Vector2f((4-(hp % 4)) * 32, 0);
quad[1].texCoords = sf::Vector2f(4-((hp % 4)) * 32 + 32, 0);
quad[2].texCoords = sf::Vector2f((4-(hp % 4)) * 32 + 32, 32);
quad[3].texCoords = sf::Vector2f((4-(hp % 4)) * 32, 32);
}
else {
sf::Vertex* quad = &m_vertices[x];
quad[0].position = sf::Vector2f(10 + x * 32,50);
quad[1].position = sf::Vector2f(10 + ((x + 1) * 32), 50);
quad[2].position = sf::Vector2f(10 + ((x + 1) * 32), 82);
quad[3].position = sf::Vector2f(10 + x * 32, 82);
quad[0].texCoords = sf::Vector2f(0, 0);
quad[1].texCoords = sf::Vector2f(0 + 32, 0);
quad[2].texCoords = sf::Vector2f(0 + 32, 32);
quad[3].texCoords = sf::Vector2f(0, 32);
}// End If else
}
}// end of function
private:
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
{
// apply the transform
states.transform *= getTransform();
states.texture = &heartTexture;
// draw the vertex array
target.draw(m_vertices, states);
}
};
and a simplified version of the main that uses it.
int main() {
sf::RenderWindow windows(sf::VideoMode(800,600), "Game");
windows.setFramerateLimit(60);
health p1Health;
p1Health.init();
p1Health.load();
while (windows.isOpen()) {
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (windows.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
windows.close();
}
windows.clear();
windows.draw(p1.charSprite);
windows.draw(box.hurtbox);
windows.draw(p1Health);
windows.display();
}
return 0;
}
however when I load up the program I see no heart, but there are no errors. Each heart image is 32*32, and there are four of them in one texture. The image is attached.