Почему зависает программа в SFML c++
Я хотел сделать игру Timber в SFML используя книгу "Beginning C++ Game Programming - Second Edition". Но когда я запускаю игру отображается в заднем плане изображение но игра немного зависает и "программа не отвечает" и выводится в консоль:
Process returned -805306369 (0xCFFFFFFF) execution time : 9.799 s
Press any key to continue.
Вот код:
// Include important C++ libraries here
#include <SFML/Graphics.hpp>
// Make code easier to type with "using namespace"
using namespace sf;
int main()
{
// Create a video mode object
VideoMode vm(1280, 800);
// Create and open a window for the game
RenderWindow window(vm, "Timber!!!", Style::Fullscreen);
// Create a texture to hold a graphic on the GPU
Texture textureBackground;
// Load a graphic into the texture
textureBackground.loadFromFile("graphics/background.png");
// Create a sprite
Sprite spriteBackground;
// Attach the texture to the sprite
spriteBackground.setTexture(textureBackground);
// Set the spriteBackground to cover the screen
spriteBackground.setPosition(0, 0);
while (window.isOpen())
{
/*
****************************************
Handle the players input
****************************************
*/
if (Keyboard::isKeyPressed(Keyboard::Escape))
{
window.close();
}
/*
****************************************
Update the scene
****************************************
*/
/*
****************************************
Draw the scene
****************************************
*/
// Clear everything from the last frame
window.clear();
// Draw our game scene here
window.draw(spriteBackground);
// Show everything we just drew
window.display();
}
return 0;
}
Но когда я изменяю:
if (Keyboard::isKeyPressed(Keyboard::Escape))
{
window.close();
}
На:
Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
Программа не зависает. Почему может быть так? Я использовал Code::Block и MinGw
Ответы (1 шт):
Вот что об этом написано на сайте самого SFML:
A mistake that people often make is to forget the event loop, simply because they don't yet care about handling events (they use real-time inputs instead). Without an event loop, the window will become unresponsive. It is important to note that the event loop has two roles: in addition to providing events to the user, it gives the window a chance to process its internal events too, which is required so that it can react to move or resize user actions.
Перевод:
Ошибка, которую часто совершают люди, заключается в том, что они забывают о цикле обработки событий просто потому, что они еще не заботятся об обработке событий (вместо этого они используют ввод данных в реальном времени). Без цикла событий окно перестанет отвечать на запросы. Важно отметить, что цикл обработки событий имеет две роли: помимо предоставления событий пользователю, он также дает окну возможность обрабатывать свои внутренние события, что необходимо для того, чтобы оно могло реагировать на перемещение или изменение размера пользователем.