★ TouchArcade needs your help. Click here to support us on Patreon.

OpenGL ES, C++, and sprite animation

11-18-2010, 11:01 AM
Joined: Sep 2010
Location: Atlanta
Posts: 184
OpenGL ES, C++, and sprite animation

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:
  1. Divide CLOCKS_PER_SEC by the frame rate you desire, say 12 (for 12 FPS)
  2. Get the difference in time of cock() and the last frame value of clock().
  3. 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.

11-18-2010, 11: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
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.

Last edited by Golden Hammer; 11-18-2010 at 11:57 AM.
11-18-2010, 12:16 PM
Joined: Sep 2010
Location: Atlanta
Posts: 184
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.
11-18-2010, 12:53 PM
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;
    uint64_t nanos = (mach_absolute_time()*base.numer)/base.denom;
    return (double)nanos*1.0e-9;

Last edited by minyx; 11-18-2010 at 12:56 PM.