问题
How would I sync sound effects with an animation (CCAnimation)
NSMutableArray* animationframes = [NSMutableArray array];
[animationframes addObject:[[[CCAnimationFrame alloc] initWithSpriteFrame:[TitleLayer spriteframeForFile:@"title_startanime01.png"] delayUnits:1 userInfo:nil] autorelease]];
[animationframes addObject:[[[CCAnimationFrame alloc] initWithSpriteFrame:[TitleLayer spriteframeForFile:@"title_startanime02.png"] delayUnits:1 userInfo:nil] autorelease]];
[animationframes addObject:[[[CCAnimationFrame alloc] initWithSpriteFrame:[TitleLayer spriteframeForFile:@"title_startanime03.png"] delayUnits:1 userInfo:nil] autorelease]];
[animationframes addObject:[[[CCAnimationFrame alloc] initWithSpriteFrame:[TitleLayer spriteframeForFile:@"title_startanime04.png"] delayUnits:1 userInfo:nil] autorelease]];
[animationframes addObject:[[[CCAnimationFrame alloc] initWithSpriteFrame:[TitleLayer spriteframeForFile:@"title_startanime05.png"] delayUnits:1 userInfo:nil] autorelease]];
[animationframes addObject:[[[CCAnimationFrame alloc] initWithSpriteFrame:[TitleLayer spriteframeForFile:@"title_startanime06.png"] delayUnits:1 userInfo:nil] autorelease]];
CCAnimation* animation = [CCAnimation animationWithAnimationFrames:animationframes delayPerUnit:0.09 loops:1];
Can I add a callblock somehow to the animationframes array?
Or it could work if a CCAnimationFrame had a optional callback/delegate for when it's activated.
回答1:
Ok all we have to do is:
Observe the notification CCAnimationFrameDisplayedNotification. It's called on the sprite that is animated.
In order for the notification to be broadcast, a dictionary will need to be added to the CCSpriteFrame that you want to hook into. I added a NSDictionary containing the spriteframename of each sprite for all spriteframes since I need to hook all of them, but I guess the dictionary could be empty as well, just not
nil
.animationframe = [[[CCAnimationFrame alloc] initWithSpriteFrame:[cache spriteFrameByName:str] delayUnits:1 userInfo:nil] autorelease]; animationframe.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:str, @"spriteframename", nil]; [animationframes addObject:animationframe]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(frameupdatedinbootanimation:) name:CCAnimationFrameDisplayedNotification object:NULL];
Then catch it
-(void)frameupdatedinbootanimation:(id)hmm {
NSLog(@"frameupdatedinbootanimation: %@", hmm);
Do something here
来源:https://stackoverflow.com/questions/19216560/syncing-sounds-with-frames-inside-ccanimation-for-cocos2d-2-x