from http://getsetgames.com/2010/04/18/how-to-animate-sprites-in-cocos2d/
CCSpriteSheet *danceSheet = [CCSpriteSheet spriteSheetWithFile:@"grossini_dance_atlas.png"];
[self addChild:danceSheet];
// create the sprite
CCSprite *danceSprite = [CCSprite spriteWithTexture:danceSheet.texture rect:CGRectMake(0, 0, 85, 121)];
[danceSheet addChild:danceSprite];
// position the sprite in the center of the screen
CGSize s = [[CCDirector sharedDirector] winSize];
danceSprite.position = ccp(s.width/2,s.height/2);
// create the animation
CCAnimation *danceAnimation = [CCAnimation animationWithName:@"dance" delay:0.1f];
int frameCount = 0;
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 5; x++) {
CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:danceSheet.texture rect:CGRectMake(x*85,y*121,85,121) offset:ccp(0,0)];
[danceAnimation addFrame:frame];
frameCount++;
if (frameCount == 14)
break;
}
}
// create the action
CCAnimate *danceAction = [CCAnimate actionWithAnimation:danceAnimation];
CCRepeatForever *repeat = [CCRepeatForever actionWithAction:danceAction];
// run the action
[danceSprite runAction:repeat];
I want the animation play when player touch the screen, so I add all above code into ccTouchesBegan like this.
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
CCSpriteSheet *danceSheet = [CCSpriteSheet spriteSheetWithFile:@"grossini_dance_atlas.png"];
[self addChild:danceSheet];
// create the sprite
CCSprite *danceSprite = [CCSprite spriteWithTexture:danceSheet.texture rect:CGRectMake(0, 0, 85, 121)];
[danceSheet addChild:danceSprite];
// position the sprite in the center of the screen
CGSize s = [[CCDirector sharedDirector] winSize];
danceSprite.position = ccp(s.width/2,s.height/2);
// create the animation
CCAnimation *danceAnimation = [CCAnimation animationWithName:@"dance" delay:0.1f];
int frameCount = 0;
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 5; x++) {
CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:danceSheet.texture rect:CGRectMake(x*85,y*121,85,121) offset:ccp(0,0)];
[danceAnimation addFrame:frame];
frameCount++;
if (frameCount == 14)
break;
}
}
// create the action
CCAnimate *danceAction = [CCAnimate actionWithAnimation:danceAnimation];
CCRepeatForever *repeat = [CCRepeatForever actionWithAction:danceAction];
// run the action
[danceSprite runAction:repeat];
}
But nothing happen except black background, although I touch the screen.
Can anyone help me???