2

我的倒计时使用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"];

}
4

3 回答 3

2
-(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"];
    }

}
于 2013-02-19T03:41:18.603 回答
1

您可以做到这一点的一种方法是跟踪方法调用之间的时间量并将其与 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?

    // beepTime is a float instance variable at first initialized to appDelegate.InGameTime - floor(appDelegate.InGameTime)
    beepTime += delta;

    if (beepTime >= 1.0f) // where 1.0f is the frequency of the beep
    {
        [[SimpleAudioEngine sharedEngine] playEffect:@"tick.mp3"];
        beepTime = appDelegate.InGameTime - floor(appDelegate.InGameTime); // should return a decimal from 0.0f to 1.0f
    }
}

我相信这应该有效。让我知道。

于 2013-02-19T03:39:54.493 回答
0

为什么不使用调度方法?

http://www.cocos2d-iphone.org/api-ref/latest-stable/interface_c_c_node.html#a7e0c230d398bba56d690e025544cb745

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

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


- (void)startBeep:(ccTime) delta
{
[[SimpleAudioEngine sharedEngine] playEffect:@"tick.mp3"];
}
于 2013-02-22T10:36:16.990 回答