Updated Sept 28, 2009: You can now hard-code the number of columns. Also included the full source code.
Updated: I fixed a bug to do with image sizing. The new download is at the end of this post.
I’m in the midst of writing my first iPhone game. I had a need to create an animation from a series of frames I produced in 3DS Max and play them back in the game. I googled the web for the best way to do this and it seems for short animations (less than 50 frames or so) like explosions and rotating asteroids the best technique for OpenGL is to stick them all together on the same texture and just change the displayed coordinates on the polygon I was using. For example:

I began by doing this myself, manually in Photoshop. What a time waster! Every time I wanted to update an animation or tweak it, it represented up to an hour of work just to do the work of resizing and stitching the images together on a grid. I then had the bright idea of automating the process. I wrote a tool in .NET that does exactly that, while preserving the alpha channel of PNG images. It sorts (by filename), resizes, stitches, and outputs the result to a neatly sized PNG graphic that can then be converted to an OpenGL texture. Remember that if you use this tool, the maximum texture size is 1024×1024 so you have to limit your animations to something that will fit in that grid.

I first tried it with an asteroid animation and it worked nicely. I’ve included the asteroid frames in the download for you to use or as an example. I also did it with an animation I made in ParticleIllusion for an explosion:

Now, on the Objective-C side of things, you need to write a class that can take these stitched assets and animate over each frame. I’ve whipped something up using the Texture2D classes provided by Apple (which I’ve augmented somewhat). Three methods are provided:
-(void)setupAnim:(int)pxWidth:(int)pxHeight:(int)frameWdth:(int)frameHt:(int)frmCnt
This takes the pixel width and height of the entire image, as well as the pixel width and height of each frame, and finally the number of frames.
-(void)incFrame
Initially the currentFrame value is set to 0 (the top left frame). You can manually set this property, or use this function incFrame() to bump it up one. When the end is reached, it will loop to the beginning.
-(void)drawFrame:(Texture2D*)animTexture:(float)x:(float)y:(float)width:(float)height:(float)rotation
This will draw the frame using the special Texture2D class I provided with an x,y, width, height, and rotation (in degrees).
If you have suggestions for a better way to do what I’m trying to do – please let me know! This utility is free to download if you find it useful, however.
Below you can see the asteroid in action!









