Creating an update method with custom rate processing in c++

145 views Asked by At

If you've ever used XNA game studio 4 you are familiar with the update method. By default the code within is processed at 60 times per second. I have been struggling to recreate such an effect in c++.

I would like to create a method where it will only process the code x amount of times per second. Every way I've tried it processes all at once, as loops do. I've tried for loops, while, goto, and everything processes all at once.

If anyone could please tell me how and if I can achieve such a thing in c++ it would be much appreciated.

2

There are 2 answers

0
snyggt On

As you are familiar with XNA then i assume you also are familiar with "input" and "draw". What you could do is assign independant threads to these 3 functions and have a timer to see if its time to run a thread.

Eg the input would probably trigger draw, and both draw and input would trigger the update method.

-Another way to handle this is my messages events. If youre using Windows then look into Windows messages loop. This will make your input, update and draw event easier by executing on events triggered by the OS.

0
SigTerm On

With your current level of knowledge this is as specific as I can get:

You can't do what you want with loops, fors, ifs and gotos, because we are no longer in the MS-DOS era.

You also can't have code running at precisely 60 frames per second.

On Windows a system application runs within something called an "event loop".

Typically, from within the event loop, most GUI frameworks call the "onIdle" event, which happens when an application is doing nothing.

You call update from within the onIdle event.

Your onIdle() function will look like this:

void onIdle(){
    currentFrameTime = getCurrentFrameTime();
    if ((currentFrameTime - lastFrameTime) < minUpdateDelay){
        sleepForSmallAmountOfTime();//using Sleep or anything. 
                                    //Delay should be much smaller than minUPdateDelay. 
                                    //Doing this will reduce CPU load.
        return;
    }
    update(currentFrameTime - lastFrameTime);
    lastFrameTime = currentFrameTime;
}

You will need to write your own update function, your update function should take amount of time passed since last frame, and you need to write a getFrameTime() function using either GetTickCount, QueryPerformanceCounter, or some similar function.

Alternatively you could use system timers, but that is a bad idea compared to onIdle() event - if your app runs too slowly.

In short, there's a long road ahead of you.

You need to learn some (preferably cross-platform) GUI framework, learn how to create a window, the concept of an event loop (can't do anything without it today), and then write your own "update()" and get a basic idea of multithreading programming and system events.

Good luck.