Sign in to follow this  

[c++ | SDL] event problem

This topic is 2325 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:
[code]
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();

[..........]
[/code]

and a game state (activeState) :

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

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 :
[code]
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;
}
}
//!

[..........]
[/code]

interesting, isn't it?

Share this post


Link to post
Share on other sites
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:
[code]
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();
}
}
[/code]

Share this post


Link to post
Share on other sites

This topic is 2325 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this