0

我正在开发一个 OpenGL ES 应用程序,我有一艘带有 6 支枪的宇宙飞船。每把枪都使用关键帧动画在开始和结束位置的 2 组顶点之间进行插值。

我有一个方法rotateGun:,我将 gunNumber 变量传递给表示应该开火的枪。开火时rotateGun:,它会产生激光爆炸,当调用该方法时,我通过指向枪管位置的矢量将其从飞船上移开。这一切都很好,但我想为每把枪的开火添加随机时间间隔,因为现在它们似乎同时开火。

我尝试使用 来创建时间延迟并启动我的 rotateGun: 方法performSelector:afterDelay:,但这不起作用。然后我尝试mainGunFire:在延迟后使用该方法,然后调用rotateGun:主线程……这也不起作用。“不起作用”是指我在rotateGun:方法中的绘图调用之前插入的 NSLog 确实打印了,但从未绘制过枪声和爆炸声。

如果我只是简单地执行 performSelectorOnMainThread 来调用rotateGun:,那么枪和爆炸会像以前一样被绘制,并且爆炸似乎同时开火。我显然不明白一些事情。有人可以帮我理解如何稍微随机化我的激光爆炸,这样它们就不会同时发射吗?谢谢!

// Randomly Fire Gun
- (void)mainGunFire:(NSNumber *)gunNumber {

    // Perform the Gun animation and fire on main thread
    [self performSelectorOnMainThread:@selector(rotateGun:) withObject:gunNumber waitUntilDone:YES];

}

// Draw and Rotate the Guns
- (void)drawRotateGuns {

    // Only shoot if this is not a ship life
    if ( self.isLife == NO ) {

        // Gun 1

        // Set the pass variable to 1 and call the method
        // after a variable amount of time
        int randomTime = 0;
        //[self performSelector:@selector(mainGunFire:) withObject:[NSNumber numberWithInt:1] afterDelay:randomTime];
        [self performSelectorOnMainThread:@selector(rotateGun:) withObject:[NSNumber numberWithInt:1] waitUntilDone:YES];

        // Gun 2 ...

        // Gun 3 ...

    }
}
4

1 回答 1

0

最简单的解决方案是使用!(rand()%some_number)而不是 1. 试验some_number价值(每支枪必须不同)。但它应该不是很大。

例如,如果您使用 2,则概率!(rand()%2) == 1约为 0.5。因此,如果您每秒渲染 60 帧,您每秒将获得大约 30 次触发。对于 !(rand()%20) 你应该每秒得到大约 3 次火灾。希望你能明白。一些伪代码:

if( !(rand()%2) ) {
     [gun1 fire];
}

if( !(rand()%3) ) {
     [gun2 fire];
}
于 2012-02-06T23:03:22.667 回答