Sprite kit, how can i randomly call a method?

百般思念 提交于 2019-12-13 04:49:01

问题


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

}

回答1:


You could use selectors to achieve your goal.

Eg.

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

An intro to selectors can be found in Cocoa Core Competencies: Selector (Apple Docs)




回答2:


This generates a random number between 0 and 7 inclusive.

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

You can then use integer stored in method to select between your various methods.



来源:https://stackoverflow.com/questions/20716328/sprite-kit-how-can-i-randomly-call-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!