Sprite Kit,我该如何随机调用方法? [英] Sprite kit, how can i randomly call a method?

查看:77
本文介绍了Sprite Kit,我该如何随机调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am programming my game at the moment in sprite kit, I have 8 differnt methods and i have it set up to call a 1 method every 5 seconds, but instead of just being able to call 1 method i want it to randomly select 1 of the 8 methods and call that. Here is my current code:

- (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];

}

推荐答案

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

You could use selectors to achieve your goal.

例如.

- (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");
}

有关抑制选择器泄漏警告的代码的更多信息,您应该参考以下问题:

For more information on the code to suppress the selector leak warning, you should refer to the following question: performSelector may cause a leak because its selector is unknown

可以在可可核心能力:选择器(Apple Docs)

这篇关于Sprite Kit,我该如何随机调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆