-1

I originally wrote my game using glfw. However due to it lack of android portability I have to replace all of my glfw code with SDL, since SDL is more portable.

My original game loop using the glfw frame work was very striaghtforward. Here it is:

// game loop
while (!glfwWindowShouldClose(window)) {
    //if-else statements that create  
    //the games state machine
    //player input is received here
    //rendering done here
}

Ok. There are probably better ways of writing this game loop, but the point is the code worked for the game prototype.

However now that I'm switching to SDL I have encountered a problem. It seems that SDL_Event has to be placed into a while loop to constantly check for events. And THIS while_loop is within another while_loop. So my code looks like this:

while(!Quit) {
    SDL_Event event;
    while(SDL_PollEvent(&event)) {
        //if-else statements that create  
        //the games state machine
        //player input is received here
        //rendering done here
    }
}

However this while_loop within a while_loop has completely messed up the games rendering! I'm now getting flickering! Is there any other way to express this code in just a single while_loop as I did earlier with glfw. Or is there any way to check for events without using an embedded while_loop

MagnusHimmler
  • 65
  • 2
  • 7
  • 4
    Shouldn't the `SDL_PollEvent()` loop just deal with events? Your rendering code and such should be outside that, in your outer loop... as is, you only render, etc. when you process an event... – Dmitri Feb 14 '17 at 15:11

1 Answers1

5

Rendering and calculations should not be done inside the event-polling loop, do it outside.

This is how I currently do it in SDL2 for a game I wrote in :

while (!quit) {
    start_frame_ms = SDL_GetTicks();

    /* Event polling */
    while (SDL_PollEvent(&event)) {
        joystick_event(&event);
        keyboard_event(&event);
    }

    /* Calculations */
    players_move();
    enemies_move();

    /* Rendering */
    draw_sprites();

    /* Lock FPS to 60 */
    end_frame_ms = start_frame_ms - SDL_GetTicks();
    if (end_frame_ms < FPMS) {
        SDL_Delay(FPMS - end_frame_ms);
    }
}
  • Another option is to have a separate thread for rendering, but that is a different story. – Dori Feb 14 '17 at 15:18
  • @Matso Wouldn't that result in coordinates from the calculations functions not be in sync with the sprites being drawn? –  Feb 14 '17 at 15:18
  • If no sync methods were applied, of course. I'm just saying that in big engines there usually are separate threads for many different things (rendering, audio, input etc.). – Dori Feb 14 '17 at 15:21
  • @Matso not sure if it is portable. I've seen deadlocked SDL_WaitEvent in that setup. – keltar Feb 15 '17 at 03:24