【问题标题】:Sprite Kit Calling a random methodSprite Kit 调用随机方法
【发布时间】:2014-01-19 16:17:06
【问题描述】:

我目前正在使用 sprite kit 制作游戏,我有 8 个方法,我已经编写了所有计时代码 E.T.C,所以它每 1 秒调用一个方法,但我希望它随机调用八种方法中的一个,我数周以来一直试图让它工作,任何帮助将不胜感激,这是我的计时代码-

- (void)updateWithTimeSinceLastUpdate:(CFTimeInterval)timeSinceLast {

    self.lastSpawnTimeInterval += timeSinceLast;
    if (self.lastSpawnTimeInterval > 5) {
        self.lastSpawnTimeInterval = 0;
        [self shoot1];
    }
}
- (void)update:(NSTimeInterval)currentTime {
    // Handle time delta.
    // If we drop below 60fps, we still want everything to move the same distance.
    CFTimeInterval timeSinceLast = currentTime - self.lastUpdateTimeInterval;
    self.lastUpdateTimeInterval = currentTime;
    if (timeSinceLast > 1) { // more than a second since last update
        timeSinceLast = 1.0 / 60.0;
        self.lastUpdateTimeInterval = currentTime;
    }

    [self updateWithTimeSinceLastUpdate:timeSinceLast];

}

如您所见,而不是[self shoot1]我希望它随机调用八个方法之一,并且所有方法都命名为Shoot1,Shoot2,一直到Shoot8。谢谢你

【问题讨论】:

标签: iphone objective-c random sprite-kit


【解决方案1】:

我能想到两个选择...

选项 1

只需在 1 到 8 之间选择一个随机数,然后使用 switch 语句:

- (void)updateWithTimeSinceLastUpdate:(CFTimeInterval)timeSinceLast {
    self.lastSpawnTimeInterval += timeSinceLast;
    if (self.lastSpawnTimeInterval > 5) {
        self.lastSpawnTimeInterval = 0;

        int randomNumber = arc4random_uniform(8);
        switch(randomNumber) {
            case 0:
                [self shoot1];
                break;
            case 1:
                [self shoot2];
                break;
            // ... cases 2-6
            case 7:
                [self shoot8];
                break;
        }
    }
}

选项 2

重写您的shootN 方法,这样您就只有一个方法可以将整数作为参数:

- (void)shoot:(int)index;

然后,您可以执行以下操作:

[self shoot:arc4random_uniform(8)];

【讨论】:

    【解决方案2】:

    你也可能过着危险的生活……

    int random = arc4random() % 8;
    NSString *selectorName = [NSString stringWithFormat:@"shoot%i", random];
    SEL selector = NSSelectorFromString(selectorName);
    if ([self respondsToSelector:selector]) {
        [self performSelector:selector];
    }
    

    顺便说一句,这会在使用 ARC 时生成警告。

    【讨论】:

      猜你喜欢
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多