0

I can't for the life of my work out why this is happening. I have in a class derived from CCLayer. I am scheduling a method call like so when initialising the class

//create an update method for keeping track of how long its been since an animation has played
    [self schedule:@selector(playIdleAnimation:)];

And the method is

//an update method that will play an idle animation after a random period of idleness
-(void) playIdleAnimation:(ccTime) dt {

//if the user isn't playing an animation, increment the time since last animation variable
if ([bodySprite numberOfRunningActions] == 0) {

    timeSinceLastAnimation += (float)dt;

    //now check to see if we have surpassed the time set to cause an idle animation
    if (timeSinceLastAnimation > (arc4random() %14) + 8) {

        //reset the cooldown timer
        timeSinceLastAnimation = 0;

        [bodySprite stopAllActions];

        //play the idle animation
        //[bodySprite runAction:[CCAnimate actionWithAnimation:waitAnimation restoreOriginalFrame:NO]]; 

        NSLog(@"PLAYING IDLE ANIMATION");
                }
}
//player is currently playing animation so reset the time since last animation
else
    timeSinceLastAnimation = 0;

}

But yet, when I go to run the program the console statements show the condition is being passed twice each cooldown

012-06-29 09:52:57.667 Test Game[5193:707] PLAYING IDLE ANIMATION

2012-06-29 09:52:57.701 Test Game[5193:707] PLAYING IDLE ANIMATION

2012-06-29 09:53:05.750 Test Game[5193:707] PLAYING IDLE ANIMATION

2012-06-29 09:53:05.851 Test Game[5193:707] PLAYING IDLE ANIMATION

I am trying to fix a bug where the game crashes when I finish playing the idle animation, and I'm certain this has something to do with it.

user819640
  • 250
  • 5
  • 14

1 Answers1

0

I don't see where you are unscheduling the selector. I bet that it's normal behavior to be called ever frame kicks in, and you see it being triggered twice because it takes a frame for the layer to be deallocated.

If you want a one-time method call, do this:

-(void) playIdleAnimation:(ccTime) dt {
    [self unschedule:_cmd];

    // rest of the code here
}

Cocos2d 2.0 has a scheduleOnce method that you can use instead.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
  • Thanks for the help, but unscheduling did not help. I managed to solve the issue by specifying the schedule interval to every 0.5 seconds. It will remain a mystery why it was being called twice. Perhaps the scheduled methods run on a thread? – user819640 Jul 10 '12 at 14:58