4
\$\begingroup\$

I know that game loop is broken up into three distinct phases: processing inputs, update, and render, but I just can't see how I can make processing input and update independent of each other.

Let's say I have a button. If I click on the button, it will increment the number by one on the screen. How can I make this possible? Is it OK to update the logic while processing the input?

For example:

 while (!ended)
 {
   while (SDL_PollEvent(&event))
   {
       IF MOUSE EVENT
          IF USER CLICKED ON THE BUTTON
              NUMBER += 1;
   }

   update(); // no job for update as number was incremented above
   draw();
 }

Why would I need a distinct update function if we could just update logic/values while processing input like the code above?

Please show me an example using SDL poll event system.

 while (!ended)
 {
   while (SDL_PollEvent(&event))
   {

   }

   update();
   draw();
 }
\$\endgroup\$
1
  • \$\begingroup\$ It's up to you. I prefer doing them separately but if you feel like to do it in the update function, go ahead \$\endgroup\$ – Kash Mar 20 '16 at 14:26
3
\$\begingroup\$

I think it all depends on how complex your game is. If it is very simple, I don't see why you couldn't updated some game states right at the input query. That is part of the game update, after all.

But you can enforce a cleaner separation in a very simple way if you want. This should also have the advantage of removing the explicit coupling of your portable game code with the SDL library. If you want to change to some other library in the future it's easier that way. Taking mouse input as an example, you could define your own MouseInput class, in pseudocode:

class MouseInput
{
    int x;
    int y;
    bool leftButtonDown;
    bool rightButtonDown;
    // etc ...
};

Then instead of directly updating some game state when you poll inputs from SDL, update your MouseInput states:

MouseInput mouse;

while (!ended)
{
    while (SDL_PollEvent(&event))
    {
        if (event == LEFT_BTN_DOWN) 
        {
            mouse.leftButton = true;
        }
        else if (event == LEFT_BTN_UP)
        {
            mouse.leftButton = false;
        }
        // same for the other buttons and the x,y cursor position.
    }

    // Now whenever something needs to know the current state of
    // the mouse it just queries the local MouseInput instance.
    //
    // It could be a class member, or you can even pass it as a parameter
    // to update() to emphasise that it is a current-frame-only state.
    //
    update(mouse);
    draw();
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.