PDA

View Full Version : OpenGL ES, C++, and sprite animation


pchukwura
11-18-2010, 10:01 AM
Just wondering what is recommended for maintaining a steady framerate with sprite animation ?

The only thing that looks useful is the clock() and CLOCKS_PER_SEC macro. (time.h)

My theory would be to:


Divide CLOCKS_PER_SEC by the frame rate you desire, say 12 (for 12 FPS)
Get the difference in time of cock() and the last frame value of clock().
If the difference is equal to or greater than CLOCKS_PER_SEC/12 then the next frame of the animation should be displayed


Would this be a correct assumption?

I'm trying to stick to C/C++ as much as possible so the core engine wouldn't be tied to the platform, which is why i'm avoiding the usage of NSDate, NSTimeInterval and such.

Thanks!

Golden Hammer
11-18-2010, 10:39 AM
Time is one of those things you want to be platform specific. I recommend you use an interface and a platform version. Then the code that uses time doesn't need to care what platform it's on.

class TimeCalculator
{
public:
virtual float getHighResTime(void) const = 0;
};

float IphoneTimeCalculator::getHighResTime(void) const
{
NSDate* date = [[NSDate alloc] init];
double doubleSecs = [date timeIntervalSinceReferenceDate];
[date release];
return (float)(doubleSecs - mStartupTime);
}

The startup time is just a trick to keep the values in a good range for float operations. I call this once per frame and pass around the result.

Edit: I did a little research and the precision of clocks is not guaranteed, so you might end up on a system where it only increments every 100ms. I usually want precision at .001 ms or better for profiling code.

pchukwura
11-18-2010, 11:16 AM
Ya, that seems to make sense to keep time platform specific, as the result could vary greatly depending on device and platform for something like time that must be precise.

This seems to be a really clean and nice approach to the problem.

minyx
11-18-2010, 11:53 AM
Use CADisplayLink to get a timer that is coupled to the screen refresh rate. On the iPhone it's trivial and involves only 2 or 3 lines of Obj-C. On the Mac you have to call some C-API methods.

To get the current time on iOS/OS X I use:


#include <sys/time.h>
#include "time.h"
#include <mach/mach.h>
#include <mach/mach_time.h>

double getDoubleTime(void)
{
mach_timebase_info_data_t base;
mach_timebase_info(&base);

uint64_t nanos = (mach_absolute_time()*base.numer)/base.denom;
return (double)nanos*1.0e-9;
}