Skip to main content
 首页 » 操作系统

swift之为 SWIFT 序列下的 repeatActionforever 内的子 Action 生成随机时间

2024年01月01日55zdz8207

您好,我试图在每次重复操作时生成随机时间间隔,但它仅在 vied 加载时才随机生成时间间隔。

这是我的代码:

 let moveBucketLeft = SKAction.moveByX(400, y: 0, duration: NSTimeInterval(grabRandomTime())) 
    let moveBucketRight = SKAction.moveByX(-400, y: 0, duration: NSTimeInterval(grabRandomTime())) 
    moveBucketLeftAndRight = SKAction.sequence([moveBucketLeft,moveBucketRight]) 
    let repeatMovement = SKAction.repeatActionForever(moveBucketLeftAndRight) 
    bucket.runAction(repeatMovement) 

grabRandomTime 方法只是生成一个介于 1 和 5 之间的随机持续时间。

我需要我能提供的所有帮助。谢谢!

这是我生成随机值的方法:

func grabRandomTime() ->UInt32{ 
    var time = arc4random_uniform(6) + 1 
    return time 
} 

并且该操作在 viewdidload 中运行一次。我想这也许就是为什么它一次只取一个随机值的原因。我不确定每次如何运行该方法。我无法在脑海中处理这个:/

请您参考如下方法:

在代码中使用 let wait = SKAction.waitForDuration(sec, **withRange**: dur) 而不是 duration: NSTimeInterval(grabRandomTime()。SKAction。带有 withRange 参数的 waitForDuration 将计算随机时间间隔,平均值 = 秒,可能的范围 = dur