SFML community forums

Help => Graphics => Topic started by: TURB0_EGG on November 02, 2017, 06:30:30 pm

Title: Draw function in custom class does not work
Post by: TURB0_EGG on November 02, 2017, 06:30:30 pm
Hello,

I wrote a class for displaying the fps of my application and the implementation looks like the following:

#include "FpsCounter.hpp"

FpsCounter::FpsCounter(sf::Vector2f position, sf::Color color) :
m_clock(),
m_text()
{
    sf::Font font;
    if (!font.loadFromFile("Arial.ttf"))
    {
        std::cerr << "Could not load font" << std::endl;
    }
    m_text.setFont(font);
    m_text.setPosition(position);
    m_text.setFillColor(color);
}

void FpsCounter::update()
{
    std::stringstream ss;
    ss << std::trunc(1 / m_clock.restart().asSeconds());
    m_text.setString(ss.str());
}

void FpsCounter::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
    states.transform *= getTransform();
    states.texture = NULL;
    target.draw(m_text, states);
}
 

The class member variables m_text and m_clock are variables of their respective types. I also implemented the draw method for easier drawing.

If I am executing a program with that fps counter it won't draw the text (and freezes) and I have no idea why. I am still pretty new to SFML (and C++ programming in general) and it would be nice if anybody could lead me into the right direction.
Title: Re: Draw function in custom class does not work
Post by: Laurent on November 02, 2017, 06:53:50 pm
The font is local to your constructor, the text will cause undefined behavior later when it will try to draw itself using it.