2013-12-21 28 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)