2013-12-21 29 views
0

我正在编写我的游戏此刻在sprite工具包中,我有8种不同的方法,并且我设置了每5秒调用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]; 

} 
+1

找到为什么不叫一个方法并传入当前的随机数,然后使用switch(number){}为每个数字运行代码? – LearnCocos2D

回答

0

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

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

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)