我使用以下代码定期生成SKNode。有没有办法使这些SKNode的生成周期随机。具体来说,如何使以下代码中的“delayFish”成为一个随机延迟的动作?
[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"];
答案 0 :(得分:6)
<强> ObjC:强>
首先设定平均延迟和范围......
#define kAverageDelay 2.0
#define kDelayRange 1.0 // vary by plus or minus 0.5 seconds
然后将您的delayFish操作更改为此...
SKAction* delayFish = [SKAction waitForDuration:kAverageDelay withRange:kDelayRange];
<强>夫特:强>
首先设定平均延迟和范围......
let averageDelay:TimeInterval = 2.0
let delayRange:TimeInterval = 1.0 // vary by plus or minus 0.5 seconds
然后将您的delayFish操作更改为此...
let delayFish = SKAction.wait(forDuration:averageDelay, withRange:delayRange)
答案 1 :(得分:0)
插入随机浮点而不是固定浮点数。
在你的情况下是这样的:
double value = ((double)arc4random() / ARC4RANDOM_MAX)
* (maxValue - minValue)
+ minValue;
SKAction* delayFish = [SKAction waitForDuration:value/_moving.speed];
我明白了。在您的情况下,这不会起作用,因为repeatActionForever将使用最后创建的随机值运行。永远。 也许试试这个。我不确定这是否有效:
SKAction* delayFish = [SKAction waitForDuration: (((double)arc4random() / ARC4RANDOM_MAX) * (maxValue - minValue)+ minValue)/_moving.speed];
我建议将随机值设为自己的方法。
-(double) getRandomValue(){
return (((double)arc4random() / ARC4RANDOM_MAX) * (maxValue - minValue)+ minValue);
}
编辑:
以下是类似问题的链接。也许这可能有所帮助。遗憾!
SKAction *randomXMovement = [SKAction runBlock:^(void){
NSInteger xMovement = arc4random() % 20;
NSInteger leftOrRight = arc4random() % 2;
if (leftOrRight == 1) {
xMovement *= -1;
}
SKAction *moveX = [SKAction moveByX:xMovement y:0 duration:1.0];
[aSprite runAction:moveX];
}];
SKAction *wait = [SKAction waitForDuration:1.0];
SKAction *sequence = [SKAction sequence:@[randomXMovement, wait]];
SKAction *repeat = [SKAction repeatActionForever:sequence];
[aSprite runAction: repeat];