1

我使用以下代码定期生成 SKNode。有没有办法让这些 SKNodes 的生成周期随机化。具体来说,如何使以下代码中的“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"];
4

2 回答 2

6

对象:

首先设置一个平均延迟和范围...

#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)
于 2014-07-25T16:49:35.453 回答
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];

资料来源:SKAction:如何为随机重复动作设置动画

于 2014-07-25T05:54:01.727 回答