I want animate some characters in my game by using a texture sprite/atlas.
The basic idea was to always only load one part of the big atlas image, the part that should be used as the character texture right now.
Is this possible? Or is my thought process wrong?
The following is my code for loading the whole texture. With the row and col arguments I want to specify which part of the atlas I want to use as my texture right now.
- (GLuint) loadTexture:(NSString*)fileName row:(int)row col:(int)col
{
NSLog(@"Loading image %@", fileName);
NSLog(@"Texture Part: %d, %d", row, col);
CGImageRef spriteImage = [UIImage imageNamed:fileName].CGImage;
if (!spriteImage) {
NSLog(@"Failed to load image %@", fileName);
exit(1);
}
size_t img_width = CGImageGetWidth(spriteImage);
size_t img_height = CGImageGetHeight(spriteImage);
GLubyte * spriteData = (GLubyte *) calloc(img_width * img_height * 4, sizeof(GLubyte));
CGContextRef spriteContext = CGBitmapContextCreate(spriteData, img_width, img_height, 8, img_width*4,
CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast);
CGContextDrawImage(spriteContext, CGRectMake(0, 0, img_width, img_height), spriteImage);
CGContextRelease(spriteContext);
GLuint texName;
glGenTextures(1, &texName);
glBindTexture(GL_TEXTURE_2D, texName);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img_width, img_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData);
free(spriteData);
NSLog(@"Texture successfully loaded!");
return texName;
}
Right now I can only load the whole image with this code, so I can only use the original image and not one small part of it to display one step of the animation.
Watch & look at some of the examples at 71Squared:
http://www.71squared.com/2009/04/iphone-game-programming-tutorial-5-animation-class/
It’s correct to load the whole texture, but when drawing you will set the texture verticies to be that of the desired column & row.
As a quick example: