Daros911
Daros911

Reputation: 435

Game loop design

I'd like to create a simple game loop. I'm taking into account this 2 versions:

v.1:

while (continueRunning) {

        PeekMessage(&msg, 0, 0, 0, PM_REMOVE);

        TranslateMessage(&msg);
        DispatchMessage(&msg);

        if (WM_QUIT == msg.message) {
            continueRunning = false;
        }

        // run the game logic

    }

and v.2:

while(continueRunning)
{
    // peek for messages
    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);

        if (msg.message == WM_QUIT)
            continueRunning = false;
    }

    // run the game logic
}

What's better solution? Is it necessary to have the PeekMessage in the while loop like in the second example?

Upvotes: 1

Views: 455

Answers (2)

Vlad Feinstein
Vlad Feinstein

Reputation: 11311

Your first version is missing an if around PeekMessage. Anyway, it will process ONE message in a game cycle (~60 per second?). That's way too slow.

You should process all messages before running your game logic, similar to your v.2.

Upvotes: 6

Alex Rowden
Alex Rowden

Reputation: 65

To the best of my knowledge, the second one is better as it will not run the TranslateMessage and DispatchMessage methods when PeekMessage returns false (or anything which converts to false). The main fallback though is that if it returns true it will run the whole loop again. This may or may not be the functionality you intend. Without knowing exactly what PeekMessage is meant to do it's difficult to provide any more insight.

Upvotes: 2

Related Questions