精灵套件,我该如何随机调用方法?

时间:2013-12-21 06:40:57

标签: iphone ios7 xcode5 sprite-kit

我正在使用精灵工具包编程我的游戏,我有8种不同的方法,我设置为每5秒调用一个方法,但不是只能调用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];

}

2 个答案:

答案 0 :(得分: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)

中找到选择器的介绍

答案 1 :(得分:0)

这将生成0到7之间的随机数。

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

然后,您可以使用method中存储的整数来选择各种方法。