Reputation: 68
Recently I've been trying to write my own game (clone of Space Invaders) using SDL but I had a problem with events... I have 2 events, one is emited by my timer, I use it to draw moving enemy ships. Second event is my keyboard event which I use to move my ship. When I start the game, enemy ships start to move exactly as I expect but if I press key or move mouse, they move slower. I have same problem while moving my ship, if I try to move mouse, frame rate slows down a lot. My event loop:
while(!exit)
{
while(SDL_PollEvent(&event));
{
if(event.type == SDL_QUIT) exit=true;
if(event.type == SDL_KEYDOWN)
{
switch(event.key.keysym.sym)
{
case SDLK_LEFT:
pship.move(pship.getPosition().x - 1, pship.getPosition().y);
break;
case SDLK_RIGHT:
pship.move(pship.getPosition().x + 1, pship.getPosition().y);
break;
}
}
if(event.type == SDL_USEREVENT)
{
switch(event.user.code)
{
case 1:
static int xOffset, yOffset;
xOffset++;
yOffset++;
drawEnemyShips(eship,xOffset,yOffset);
break;
}
}
}
}
I use Visual c++ 2010 express and SDL 1.2.15
Upvotes: 1
Views: 529
Reputation: 182883
while(SDL_PollEvent(&event));
You definitely don't want that ;
on there! The way you have it, you are eating events. If you get an event, SDL_PollEvent
returns one, so you call SDL_PollEvent
again. If there's no event, you break out of the while
loop and process it. But if there's a second event, you never process the first.
But in any event, a spinning poll loop is broken. It's like the kid who keeps asking "Are we there yet" every minute and doesn't let the parents drive. Use SDL_WaitEvent
to wait for an event rather than spinning the CPU polling for one.
A simple way to do it is to change:
while(SDL_PollEvent(&event));
to this:
while (SDL_WaitEvent(&event) != 0)
That will leave your code a bit clumsy (the while
loop is still needless, when you break out of it, you just re-enter it), but at least it will not be broken.
Upvotes: 6