Search code examples
objective-cmethodssprite-kitskspritenodeskaction

SpriteKit - Run a method with two arguments after a random period of time


While trying to create a game for iOS I'm facing a problem: I cannot find a way to call a method that creates a SpriteKit node from another class that "calls itself" or repeats after a random period of time in an easy way.

The idea is this: I have a class where the scene is created. But then I have another class (subclass of SKSPriteNode) that creates the different SKSpriteNode that I need. I have one method called createObjectWithName: name position: position that takes two arguments (name and position). I need to call this method from my scene (fine until here), but I also need to repeat this method constantly in random periods of time. So, once it is called one time, it calls itself after a period of time, creating more SKSPriteNodes.

I've tried using performSelector and dispatch_after, but I hadn't had any luck so far.

Thank you in advance.


Solution

  • Unless I am missing something, I think you want to use SKAction for this solution.

    You could have a method for starting the spawner like this :

    -(void)startSpawner:(float)duration range:(float)range
    {
    
        SKAction *delay = [SKAction waitForduration:duration withRange:range];
        SKAction *spawnBlock = [SKAction runBlock:^(void)
                                {
    
                                    NSString *spawnName = @"name";
                                    CGPoint *spawnPosition = CGPointMake(someX, someY);
                                    SpriteNodeSubclass *node = [SpriteNodeSubclass createObjectWithName:spawnName andPosition:spawnPosition];
                                    // do something with that node if you need to.
                                }];
    
        SKAction *sequence = [SKAction sequence:@[delay, spawnBlock]];
        SKAction *repeat = [SKAction repeatActionForever:sequence];
        [self runAction:repeat];
    }
    

    I think it's ideal to use SKAction as opposed to dispatch_after, because if you pause SpriteKit, the SKAction will also pause.