随机化节点移动持续时间 [英] Randomizing node movement duration
问题描述
我正在 SpriteKit 中制作游戏,我有一个节点在屏幕上来回移动并使用代码重复:
I am making a game in SpriteKit and I have a node that is moving back and forth across the screen and repeating using the code:
let moveRight = SKAction.moveByX(frame.size.width/2.8, y: 0, duration: 1.5)
let moveLeft = SKAction.moveByX(-frame.size.width/2.8, y: 0, duration: 1.5)
let texRight = SKAction.setTexture(SKTexture(imageNamed: "Drake2"))
let texLeft = SKAction.setTexture(SKTexture(imageNamed: "Drake1"))
let moveBackAndForth = SKAction.repeatActionForever(SKAction.sequence([texRight, moveRight, texLeft, moveLeft,]))
Drake1.runAction(moveBackAndForth)
我想弄清楚我可以使用什么方法来随机化持续时间.每次 moveBackandForth 运行时,我希望它使用不同的持续时间重新运行(在游戏内,而不是在游戏之间).如果有人可以给我一些示例代码来尝试,我将不胜感激.
I am trying to figure out what method I can use to randomize the duration. Every time moveBackandForth runs, I want it to rerun using a different duration, (within games, not between). If someone could give me some example code to try I would really appreciate it.
arc4Random 也可以正常工作,但它不会在游戏内随机化,只会在游戏之间随机化.
Also arc4Random works fine, but it doesn't randomize within the game, only between games.
推荐答案
当您运行示例中的操作并使用 arc4Random 之类的东西随机化持续时间参数时,这实际上正在发生:
When you run actions like from your example and randomize duration parameter with something like arc4Random this is actually happening:
- 随机持续时间设置并存储在动作中.
- 然后在给定持续时间的序列中重复使用操作.
因为动作被原样重复使用,持续时间参数随着时间的推移保持不变,移动速度不是随机的.
Because the action is reused as it is, duration parameter remains the same over time and moving speed is not randomized.
解决这个问题的一种方法(我个人更喜欢)是创建一个递归操作",或者更好地说,创建一个方法来运行所需的序列并像这样递归地调用它:
One way to solve this (which I prefer personally) would be to create a "recursive action", or it is better to say, to create a method to run desired sequence and to call it recursively like this :
import SpriteKit
class GameScene: SKScene {
let shape = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 20, height: 20))
override func didMoveToView(view: SKView) {
shape.position = CGPointMake(CGRectGetMidX(self.frame) , CGRectGetMidY(self.frame)+60 )
self.addChild(shape)
move()
}
func randomNumber() ->UInt32{
var time = arc4random_uniform(3) + 1
println(time)
return time
}
func move(){
let recursive = SKAction.sequence([
SKAction.moveByX(frame.size.width/2.8, y: 0, duration: NSTimeInterval(randomNumber())),
SKAction.moveByX(-frame.size.width/2.8, y: 0, duration: NSTimeInterval(randomNumber())),
SKAction.runBlock({self.move()})])
shape.runAction(recursive, withKey: "move")
}
}
要停止动作,请移除它的键(move").
To stop the action, you remove its key ("move").
这篇关于随机化节点移动持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!