定时器条件使用cocos2d调度程序传递两次

时间:2012-06-29 09:04:20

标签: timer cocos2d-iphone conditional-statements schedule cclayer

我不能为我的工作生活解释为什么会这样。我有一个来自CCLayer的类。在初始化类

时,我正在调度方法调用
//create an update method for keeping track of how long its been since an animation has played
    [self schedule:@selector(playIdleAnimation:)];

方法是

//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;

}

但是,当我去运行程序时,控制台语句显示每个冷却时间被传递两次

012-06-29 09:52:57.667测试游戏[5193:707]播放空闲动画

2012-06-29 09:52:57.701测试游戏[5193:707]播放空闲动画

2012-06-29 09:53:05.750测试游戏[5193:707]播放空闲动画

2012-06-29 09:53:05.851测试游戏[5193:707]播放空闲动画

我正在尝试修复当我完成播放空闲动画时游戏崩溃的错误,我确信这与它有关。

1 个答案:

答案 0 :(得分:0)

我看不到你在哪里取消选择。我敢打赌,一直被称为框架踢的正常行为,你会看到它被触发两次,因为它需要一个框架才能解除分层。

如果您想要一次性方法调用,请执行以下操作:

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

    // rest of the code here
}

Cocos2d 2.0有一个scheduleOnce方法,您可以使用它。