Skip to content

Instantly share code, notes, and snippets.

@andrewtremblay
Last active September 13, 2018 07:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewtremblay/bfce7cffe595551e5633 to your computer and use it in GitHub Desktop.
Save andrewtremblay/bfce7cffe595551e5633 to your computer and use it in GitHub Desktop.
SpriteKit helper function for building loops from TextureAtlases
// Assumes consistent file names accross all image sequences (mine are zero-indexed and padded to five digits)
// mainCharacter.atlas
// - idleLoop_00000.png
// - idleLoop_00001.png
// - ...
// - walkLoop_00000.png
// - walkLoop_00001.png
// - ...
- (void)loadAnimations{
SKAction *animLoopIdle = [self buildLoopFromAtlas:@”mainCharacter” withFileNameFormat:@”idleLoop_%0.5d”];
SKAction *animLoopWalk = [self buildLoopFromAtlas:@”mainCharacter” withFileNameFormat:@”walkLoop_%0.5d”];
}
-(SKAction *)buildLoopFromAtlas:(NSString *)atlasName withFileNameFormat:(NSString *)fileFormat {
SKTextureAtlas *loopAtlas = [SKTextureAtlas atlasNamed:atlasName];
NSMutableArray *atlasArray = [NSMutableArray array];
NSString *fileNameRegex = [[fileFormat substringToIndex:(fileFormat.length - @"%0.5d".length)] stringByAppendingString:@"[0-9]{5}.png"];
NSPredicate *matchesBaseFilename = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", fileNameRegex];
NSArray *matchingTextures = [loopAtlas.textureNames filteredArrayUsingPredicate:matchesBaseFilename];
for(int i=0; i < matchingTextures.count; i++){
NSString *textureName = [NSString stringWithFormat:fileFormat, i];
SKTexture *tex = [loopAtlas textureNamed:textureName];
[atlasArray addObject:tex];
}
NSTimeInterval fps24 = (NSTimeInterval)(1.0/24.0);
SKAction *animation = [SKAction animateWithTextures:atlasArray timePerFrame:fps24 resize:YES restore:YES];
return [SKAction repeatActionForever:animation];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment