Syncing sounds with frames inside CCAnimation for

2019-09-02 03:36发布

问题:

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:

  1. Observe the notification CCAnimationFrameDisplayedNotification. It's called on the sprite that is animated.

  2. 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