Last Updated: February 20, 2016
·
942
· insanehunter

CCSprite category for making switch to texture atlases easier

When working on a cocos2d-iphone game, use the following CCSprite category to make switch to texture atlases much easier in future:

// CCSpriteExtensions.h

#import "cocos2d.h"

@interface CCSprite (Extensions)
+ (id) spriteWithSpriteFrameNameOrFile:
                             (NSString *)nameOrFile;
@end


// CCSpriteExtensions.m
#import "CCSpriteExtensions.h"

@implementation CCSprite (Extensions)
+ (id) spriteWithSpriteFrameNameOrFile:
                             (NSString *)nameOrFile
{
    CCSpriteFrame* spriteFrame = 
         [[CCSpriteFrameCache sharedSpriteFrameCache]
                spriteFrameByName:nameOrFile];
    if (spriteFrame)
        return [CCSprite spriteWithSpriteFrame:spriteFrame];
    return [CCSprite spriteWithFile:nameOrFile];
}
@end

This idea and code taken from A helpful CCSprite code gem.