Search code examples
iosrandomsprite-kitskactionsknode

SKAction: how to generate a random delay in generation of nodes


I use the following piece of code to generate SKNodes periodically. Is there a way to make the period of generation of these SKNodes random. Specifically, how do I make the "delayFish" in the following code an action with a random delay?

[self removeActionForKey:@"fishSpawn"];
SKAction* spawnFish = [SKAction performSelector:@selector(spawnLittleFishes) onTarget:self];
SKAction* delayFish = [SKAction waitForDuration:3.0/_moving.speed];
SKAction* spawnThenDelayFish = [SKAction sequence:@[spawnFish, delayFish]];
SKAction* spawnThenDelayFishForever = [SKAction repeatActionForever:spawnThenDelayFish];
[self runAction:spawnThenDelayFishForever withKey:@"fishSpawn"];

Solution

  • ObjC:

    First set an average delay and range...

    #define kAverageDelay    2.0
    #define kDelayRange      1.0     // vary by plus or minus 0.5 seconds
    

    and then change your delayFish action to this...

    SKAction* delayFish = [SKAction waitForDuration:kAverageDelay withRange:kDelayRange];
    

    Swift:

    First set an average delay and range...

    let averageDelay:TimeInterval = 2.0
    let delayRange:TimeInterval = 1.0     // vary by plus or minus 0.5 seconds
    

    and then change your delayFish action to this...

    let delayFish = SKAction.wait(forDuration:averageDelay, withRange:delayRange)