Day 8: Animation again, and frame times

January 9, 2010 by pekuja · Leave a Comment 

I was hoping to write a bit of a longer post tonight, but I ended up taking a long nap and not having time to write a lot of new code. I do have some things I want to write about though.

What I did do today is I rewrote my animation system to work with my new base code. It isn’t quite as nice as the one I was using previously, but I can always extend it further if I need more. My current system uses one animation per file, with the individual frames in a grid. The animation speed is based on number of game ticks to display a frame of animation. I could had used a temporal frame length instead, but I figured I don’t want there to be jitter where the actual frame length varies due to game ticks not being in sync.

I also added some code to fix my frame rate. Simple enough, just check how long it’s been since the last frame and sleep for an appropriate amount of time to fix the game loop to a steady frame rate. I bumped into some weird issues with my simple code though. I was fixing the frame rate to 30FPS, but as it turns out, the game was running at 60FPS instead. What’s even stranger, is I examined my game’s CPU usage, and when I had the game set to 30FPS, the CPU usage was very low. Just a couple of percent. When I turned the FPS up even just a little bit though, the CPU usage jumped to 50%, which on a dual core system means it was pretty much running as fast as it could. I’m still not sure what exactly was happening there, but I did eventually figure out that the problem was that the sleep function wasn’t really very accurate, so it was actually sleeping a lot less than I wanted it to, which is why the game was running at 60FPS instead of 30FPS. As for the CPU usage, I think what was happening is that when I upped the target FPS, I started to hit the vsync more often, for whatever magic reason. The graphics driver uses a busy loop to wait for vsync, so that hogs all the CPU it can get. It would be interesting to examine what was happening exactly, but the way I fixed the problem is I changed my sleep period to accumulate the error from previous frames. That way, even though the sleep function isn’t quite accurate, the error accumulation fixes the error on average.