Objective c 如何每秒播放一次嘟嘟声Cocos2d

Objective c 如何每秒播放一次嘟嘟声Cocos2d,objective-c,cocos2d-iphone,Objective C,Cocos2d Iphone,使用每帧更新的InGameTime值每秒更新我的倒计时 这在视觉上非常有效,因为我可以将游戏时间四舍五入到最接近的整数 …但如何让我的应用程序在每秒钟后播放一声蜂鸣音 下面是我的代码: -(void) setTimer:(ccTime) delta{ int timeInSeconds = (int)appDelegate.InGameTime;//Game time E.G: 8.2332432 /* Stuff is here to display

使用每帧更新的
InGameTime
值每秒更新我的倒计时

这在视觉上非常有效,因为我可以将游戏时间四舍五入到最接近的整数

…但如何让我的应用程序在每秒钟后播放一声蜂鸣音

下面是我的代码:

-(void) setTimer:(ccTime) delta{

    int timeInSeconds = (int)appDelegate.InGameTime;//Game time E.G: 8.2332432
    /*

            Stuff is here to display the tempTime

    */


    //The below effect plays the sound every frame, 
    //is there an equation that I can apply to appDelegate.InGameTime 
    //that will play it once a second?

    [[SimpleAudioEngine sharedEngine] playEffect:@"tick.mp3"];

}

一种方法是跟踪方法调用之间的时间量,并将其与InGameTime关联

e、 g


我认为这应该行得通。让我知道。

为什么不使用计划方法

-(void) setTimer:(ccTime) delta{

    static float timeSinceLastTick = 0.f;

    int timeInSeconds = (int)appDelegate.InGameTime;//Game time E.G: 8.2332432
    /*

        Stuff is here to display the tempTime

    */

    // if your delta is small and relatively constant, this 
    // should be real close to what you want.
    // other ways exist

    timeSinceLastTick += delta;
    if (timeSinceLastTick > 1.0f) {
       timeSinceLastTick=0.f;
       [[SimpleAudioEngine sharedEngine] playEffect:@"tick.mp3"];
    }

}

您只需指定间隔,然后将要触发的代码放入块内

//call startBeep function every 1 second
[self schedule:@selector(startBeep:) interval:1.0f];


- (void)startBeep:(ccTime) delta
{
[[SimpleAudioEngine sharedEngine] playEffect:@"tick.mp3"];
}

看看你是否可以使用NSTimer,我已经在我的一个应用程序中使用了相同的方法。顺便说一句,这可能不是最有效或一致的方法。也许其他人可以提出我的建议,或者提供另一个建议。谢谢你,我和YvelBeg一起去了,因为这是一个稍微简单的解决方案,但是我想给你一个同样的想法。我只是想指出,我确实考虑了与YVES相同的解决方案,并拒绝了。虽然它确实每秒滴答一次,但它也可能无法与游戏时间标签正确同步,因为该函数可能不会在整秒钟内正确调用。我的解决方案解释了这一点,这是造成额外复杂性的原因。请注意,尽管这确实每秒触发一次,但它也可能无法与游戏时间正确同步,具体取决于此方法首次计划和运行的时间。
//call startBeep function every 1 second
[self schedule:@selector(startBeep:) interval:1.0f];


- (void)startBeep:(ccTime) delta
{
[[SimpleAudioEngine sharedEngine] playEffect:@"tick.mp3"];
}