A helpful CCSprite code gem …

On January 14, 2011, in cocos2d, Programming, by Steffen Itterheim

I often start out with new code using dummy graphics. Until I figure out what exactly I need and what is going to work, I work with single image files added to the project’s resources. Creating a texture atlas is always the last step I do, once everything is settled. Creating and updating a Texture Atlas adds just a few extra steps but I always strive to avoid any unnecessary extra steps during a creative working period. Especially while experimenting. Any repetitive task hampers creativity.

But eventually, I will have to go in and change every CCSprite initialization code from spriteWithFile to spriteWithSpriteFrameName. Except, I don’t.

The following is a simple extension category for CCSprite that extends CCSprite with a spriteWithSpriteFrameNameOrFile initializer. It looks for the given file name in the CCSpriteFrameCache. If it exists as CCSpriteFrame, it uses that sprite frame and otherwise it reverts back to loading the sprite from file. Very easy, very helpful.

// CCSpriteExtensions.h

#import "cocos2d.h"

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

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

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