2014-01-19 48 views
1

我目前正在製作一個sprite套件中的遊戲,並且我有8種方法,我寫了所有的時間碼ETC,因此每1秒調用一次方法,但是我希望它隨機調用一個方法八大方法,我一直在努力得到這個工作好幾個星期,任何幫助將長久地感謝,這是我的時刻碼 -Sprite Kit調用隨機方法

- (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。三江源

+1

[Sprite工具包,我怎麼可以隨機調用一個方法?](http://stackoverflow.com/questions/20716328/sprite-kit-how-can-i-randomly-call-a-method) – 2014-04-17 12:21:51

+0

是的,我無法刪除,因爲它有答案 – user3110546

回答

2

我能想到的兩個選項...

選項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)]; 
1

你也可以住危險...

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

順便說一句,這會在使用ARC時產生警告。