Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SDL2 main game loop

My question popped out while reading the tutorials on SDL2, on lazyfoo.net and the code is being copied from this page

int main( int argc, char* args[] )
{

//Start up SDL and create window

if( !init() )
{
    printf( "Failed to initialize!\n" );
}
else
{
    //Load media
    if( !loadMedia() )
    {
        printf( "Failed to load media!\n" );
    }
    else
    {
        //Main loop flag
        bool quit = false;

        //Event handler
        SDL_Event e;

        //While application is running
        while( !quit )
        {
            //Handle events on queue
            while( SDL_PollEvent( &e ) != 0 )
            {
                //User requests quit
                if( e.type == SDL_QUIT )
                {
                    quit = true;
                }
            }

            //Clear screen
            SDL_RenderClear( gRenderer );

            //Render texture to screen
            SDL_RenderCopy( gRenderer, gTexture, NULL, NULL );

            //Update screen
            SDL_RenderPresent( gRenderer );
        }
    }
}

//Free resources and close SDL
close();

return 0;
}

Here why are we rendering the effects inside the main loop and make it run again and again rather than like:

int main( int argc, char* args[] )
{
//Start up SDL and create window
if( !init() )
{
    printf( "Failed to initialize!\n" );
}
else
{
    //Load media
    if( !loadMedia() )
    {
        printf( "Failed to load media!\n" );
    }
    else
    {
        //Main loop flag
        bool quit = false;

        //Event handler
        SDL_Event e;

       //Clear screen
       SDL_RenderClear( gRenderer );

        //Render texture to screen
        SDL_RenderCopy( gRenderer, gTexture, NULL, NULL );

        //Update screen
        SDL_RenderPresent( gRenderer );

        //While application is running
        while( !quit )
        {
            //Handle events on queue
            while( SDL_PollEvent( &e ) != 0 )
            {
                //User requests quit
                if( e.type == SDL_QUIT )
                {
                    quit = true;
                }
            }
        }
    }
}

//Free resources and close SDL
close();

return 0;
}

I suppose there is a reason as this is done in many tutorials. But i am unable to get the reason.

like image 218
Sagar Kar Avatar asked Mar 15 '23 18:03

Sagar Kar


1 Answers

You render the screen again and again because typically things represented on the screen are changing. To represent those changes you need to update the display. For example, if a ball is moving across the screen and you only render the screen once, the ball will not appear to move. However, if you continue to "run again and again" then you will be able to see the ball move across the screen.

like image 81
Joseph Hutchinson Avatar answered Mar 30 '23 04:03

Joseph Hutchinson