Jump to content
  • Advertisement
Sign in to follow this  
Szymon?agosz

[c++ | SDL] event problem

This topic is 2538 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, this is my first post here.
I have a problem which i can't sort out.

this is part of my game engine:

void Game::run()
{
Timer fps;
SDL_Event event;

fps.start();

while(!isQuit && activeState) {


//app x-ed or ESC => quit
while(SDL_PollEvent(&event)) {
if(event.type == SDL_QUIT || (
(event.type == SDL_KEYDOWN) && event.key.keysym.sym == SDLK_ESCAPE))
{
isQuit = true;
continue;
}
}
//!

activeState->handle_events();
activeState->logic();
activeState->render();

[..........]


and a game state (activeState) :


void Intro::handle_events()
{
while(SDL_PollEvent(&event)) {
if(event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE)
exit(3); //or anything else
}
}


The problem is that computer doesnt recognize events in Intro class. It changes if i comment out handling event in the Game class.
Why is it so?


//EDIT

dont know why but when i swap some part of code it started working properly :

void Game::run()
{
Timer fps;
SDL_Event event;

fps.start();

while(!isQuit && activeState) {


activeState->handle_events();
activeState->logic();
activeState->render();

//app x-ed or ESC => quit
while(SDL_PollEvent(&event)) {
if(event.type == SDL_QUIT || (
(event.type == SDL_KEYDOWN) && event.key.keysym.sym == SDLK_ESCAPE))
{
isQuit = true;
continue;
}
}
//!

[..........]


interesting, isn't it?

Share this post


Link to post
Share on other sites
Advertisement
You're polling events in two places. When you poll an event, it is moved from the event queue into your local event variable. If you don't handle it, it is effectively lost.

The solution is to centralise your event handling, that way you'll never have one event loop dropping events that another loop thinks is important.

Example:

class State
{
public:
// ...

virtual void handle_event(const SDL_Event &event);

// ...
};

void Game::run()
{
Timer fps;
fps.start();

while(!isQuit && activeState)
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
if(event.type == SDL_QUIT || ((event.type == SDL_KEYDOWN) && event.key.keysym.sym == SDLK_ESCAPE))
{
isQuit = true;
}
else
{
activeState->handle_event(event);
}
}

activeState->logic();
activeState->render();
}
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!