RawMean RawMean - 4 months ago 15
iOS Question

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

Answer

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:NSTimeInterval = 2.0
let delayRange:NSTimeInterval = 1.0     // vary by plus or minus 0.5 seconds

and then change your delayFish action to this...

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