Skip to content

Instantly share code, notes, and snippets.

@jpavley
Last active September 24, 2015 22:27
Show Gist options
  • Save jpavley/818754 to your computer and use it in GitHub Desktop.
Save jpavley/818754 to your computer and use it in GitHub Desktop.
Change a Cocos2D-iPhone sprite's image using a CCSpriteFrame from the CCSpriteFrameCache.
// Assumes you've created a texture atlas with at least 2 image init:
// initial_image.png and new_image.png
// Load the texture atlas into the shared frame cache early in your game…
CCSpriteFrameCache* frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
[frameCache addSpriteFramesWithFile:@"textureAtlas.png"];
// Create your sprite in your layer’s – init method…
// (Note: niceSprite is a CSprint* instance variable so we can reuse it)
niceSprite = [CCSprite spriteWithSpriteFrameName:@"initial_image.png"];
niceSprite.position = CGPointMake(240, 160);
[self addChild:niceSprite z:0 tag:0];
// in your – ccTouchBegan or – ccTouchesBegan method add the following code
// to change the image associated with your sprite…
CCSpriteFrameCache* frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
CCSpriteFrame* frame = [frameCache spriteFrameByName:@"new_image.png"];
[niceSprite setDisplayFrame:frame];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment