Poor handling of events [SFML]


Nesesito know why my program exploits for no reason, and how could I solve it, I'm moving in the architecture of a game, very simple, for now I only have the class Stage that serves as the main event which drew in the window everything that I add. I try to use as much as I can, the iterator design pattern.

This is Stage.h :

#pragma once
#include <SFML\Graphics.hpp>
#include <vector>

class Stage {
    sf::RenderWindow *window;
    std::vector <sf::Sprite> all_sprites;
    Stage           ();
    Stage           (int width, int height, sf::String name);

    void addObj     (sf::Sprite newobject);
    void removeObj  (sf::Sprite ocurrence);

    void renderize  ();
    void run        ();

This is Stage.cpp :

#include "Stage.h"
#include <SFML\Graphics.hpp>
#include <iostream>
#include <vector>

Stage::Stage() { window = nullptr; }

Stage::Stage(int width, int height, sf::String name) {
    window = new sf::RenderWindow(sf::VideoMode(width, height), name);

void Stage::addObj(sf::Sprite obj) { all_sprites.push_back(obj); }

void Stage::removeObj(sf::Sprite obj) {
    for (auto it = all_sprites.begin(); it != all_sprites.end(); it++) {
        if ((*it).getPosition() == obj.getPosition()) {

void Stage::renderize() {
    for (auto it = all_sprites.begin(); it != all_sprites.end(); it++) { window->draw(*it); }

void Stage::run() {
    while (window->isOpen()) {
        sf::Event event;
        while (window->pollEvent(event)) {
            if (event.type == sf::Event::Closed) window->close();
            if (event.key.code == sf::Keyboard::Escape) window->close();
            if (event.type == sf::Event::MouseButtonPressed) {
                if (event.mouseButton.button == sf::Mouse::Left) {
                    std::cout << "Left click detected!" << std::endl;

finally this is my main.cpp :

#include "Stage.h"
#include <SFML\Graphics.hpp>

int main() {
    Stage app(640, 480, "Game #1");
    sf::Texture text;
    sf::Sprite sprite(text);
    return 0;

The program perfectly fulfills the syntax, the logic I see it all well and I do not even get any warning. But when I run it the program simply closes itself after about 2 seconds, I've also noticed that adding a click event increases this time by extending the life of the program, but in the end the same thing happens. I want it to run until I give it esc or click on the close button, I do not know why my infinite while has an end.

What do you recommend I do to solve it?

asked by Egon Stetmann. 05.11.2017 в 17:58

1 answer


I solved the problem by adding a clock to synchronize the fps of the game, that way the events have a time defined by frame:


With this fact the events are handled properly since we put them under synchronization of the system clock.

It's all I could understand after exhaustively reading the documentation. I know it's not a good answer but maybe someone will do this.

answered by 16.11.2017 / 04:12