【问题标题】:Sprite kit, how can i randomly call a method?Sprite kit,我如何随机调用方法?
【发布时间】:2014-01-10 01:34:41
【问题描述】:

我目前正在使用 sprite kit 编写游戏,我有 8 种不同的方法,我将其设置为每 5 秒调用 1 个方法,但我希望它随机调用 1 个方法,而不是仅仅能够调用 1 个方法选择 8 个方法中的 1 个并调用它。这是我当前的代码:

- (void)updateWithTimeSinceLastUpdate:(CFTimeInterval)timeSinceLast {

    self.lastSpawnTimeInterval += timeSinceLast;
    if (self.lastSpawnTimeInterval > 5) {
        self.lastSpawnTimeInterval = 0;
        [self shootPizza];
    }
}
- (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];

}

【问题讨论】:

  • 为什么不只调用一个方法并传入当前随机数,然后使用 switch(number){} 为每个数字运行代码?

标签: iphone ios7 xcode5 sprite-kit


【解决方案1】:

您可以使用选择器来实现您的目标。

例如。

- (IBAction)performRandomMethod:(id)sender {

    // put the method names as NSStrings into an array
    // selectors are not objects, thus we convert to NSValue to allow storage in NSArray
    NSArray *applicableMethods = @[[NSValue valueWithPointer:@selector(doA)],
                                   [NSValue valueWithPointer:@selector(doB)],
                                   [NSValue valueWithPointer:@selector(doC)]];

    // randomly pick one of the objects from the array and convert back to a selector
    NSUInteger randomIndex = arc4random_uniform(applicableMethods.count);
    SEL randomMethodSelector = [[applicableMethods objectAtIndex:randomIndex] pointerValue];

    // perform the selector
    // ARC may complain regarding a selector leak - we can suppress with the following pragma marks
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [self performSelector:randomMethodSelector withObject:nil];
#pragma clang diagnostic pop


}

- (void)doA {
    NSLog(@"doA");
}

- (void)doB {
    NSLog(@"doB");
}

- (void)doC {
    NSLog(@"doC");
}

有关抑制选择器泄漏警告的代码的更多信息,您应该参考以下问题:performSelector may cause a leak because its selector is unknown

选择器的介绍可以在Cocoa Core Competencies: Selector (Apple Docs)中找到

【讨论】:

    【解决方案2】:

    这会生成一个介于 0 和 7 之间的随机数。

    #include <stdlib.h>
    ...
    ...
    int method = arc4random() % 8;
    

    然后您可以使用存储在method 中的整数在各种方法之间进行选择。

    【讨论】:

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