Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Draw function in custom class does not work  (Read 1439 times)

0 Members and 1 Guest are viewing this topic.

TURB0_EGG

  • Newbie
  • *
  • Posts: 1
    • View Profile
Draw function in custom class does not work
« 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.

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32504
    • View Profile
    • SFML's website
    • Email
Re: Draw function in custom class does not work
« Reply #1 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.
Laurent Gomila - SFML developer

 

anything