Search code examples
c++sfml

How to override sf::Drawable::draw()


Try to make a caro game with SFML so first I try to display a rectangle on window using sf::Drawable but I can not see the my rectangle on Window.

I just declare a Game object and call run() in my main() function. Game.cpp

#include "Game.h"

Game::Game() : mWindow(sf::VideoMode(800, 600), "SFML Button"),
sn(sf::Vector2f(20.f, 20.f), sf::Color::Blue)
{
    
}

void Game::run()
{
    while (mWindow.isOpen()) {
        mWindow.clear(sf::Color::Black);
        mWindow.display();
        render();

    }
}

void Game::render()
{
    mWindow.draw(sn);
}

SceNode.h

#ifndef _GAME_H_
#define _GAME_H_
#include <SFML/Graphics.hpp>
#include "SceneNode.h"
class Game
{
public:
    Game();
    void run();
private:

    void render();
    void update();
    void ProcessEvent();
private:
    SceneNode sn;
    sf::RenderWindow mWindow;
    
};
#endif // !_GAME_H_

SceneNode.cpp

#include "SceneNode.h"

SceneNode::SceneNode(sf::Vector2f vector, sf::Color c) : rect(vector)
{
    rect.setPosition(0.f, 0.f);
    rect.setFillColor(sf::Color::Red);
}

void SceneNode::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
    target.draw(rect, states);
}

I didn't know what to fix.


Solution

  • I think you got so convinced that the problem is with overriding that you didn't consider that the problem could be something completely different.

    The appropriate order of operations is clear, then draw, then display.

    You do clear, then display, then draw, so you display the recently cleared image, then draw some stuff which you immediately clear.

    This change should do it:

    while (mWindow.isOpen()) {
        mWindow.clear(sf::Color::Black);
        render();
        mWindow.display();
    }