【问题标题】:OpenGL ES Perform Selector After Random DelayOpenGL ES 在随机延迟后执行选择器
【发布时间】:2012-02-01 02:04:32
【问题描述】:

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

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

我尝试使用performSelector:afterDelay: 创建一个时间延迟并启动我的 rotateGun: 方法,但这不起作用。然后我尝试在延迟后使用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 ...

    }
}

【问题讨论】:

  • [NSNumber numberWithInt:1] - 插入随机值而不是 1。一般来说你的方法在设计上是错误的,我建议使用现成的开源引擎 ;)
  • 好的,感谢您的意见!

标签: objective-c ios cocoa opengl-es performselector


【解决方案1】:

最简单的解决方案是使用!(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];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 2013-05-21
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多