如何制作随机重复动作的动画?
如何使 SKAction.move() 随机且永远重复?
例如:
let boxPosition = Double.random(in: 100…600)
let boxMove = SKAction.move(to: CGPoint(x: boxPosition, y: 100), duration: 10)
let boxRepeat = SKAction.repeatForever(boxMove)
box.run(boxRepeat)
我知道在上面的示例中不会更新值......
我有一个可行的解决方案,但感觉不正确。该序列不起作用...
import SpriteKit
class GameScene: SKScene {
let box = SKSpriteNode()
override func didMove(to view: SKView) {
box.texture = SKTexture(imageNamed: "box")
box.size = CGSize(width: 50, height: 50)
box.position = CGPoint(x: 200, y: 200)
addChild(box)
let boxRandom = SKAction.run({
let boxPosition = Double.random(in: 300...500)
let boxMove = SKAction.move(to: CGPoint(x: 200, y: boxPosition), duration: 2)
self.box.run(boxMove)
})
let boxMove = SKAction.move(to: CGPoint(x: 200, y: 100), duration: 2)
let boxGroup = SKAction.sequence([boxMove, boxRandom])
let boxRepeat = SKAction.repeatForever(boxGroup)
box.run(boxRepeat)
}
}
有什么建议吗?感谢您提前提供的所有答案。
How can I make SKAction.move() to be random and repeatForever?
For example:
let boxPosition = Double.random(in: 100…600)
let boxMove = SKAction.move(to: CGPoint(x: boxPosition, y: 100), duration: 10)
let boxRepeat = SKAction.repeatForever(boxMove)
box.run(boxRepeat)
I know that in above example will not update the value…
I have solution that works but doesn't feel right. The sequence won't work...
import SpriteKit
class GameScene: SKScene {
let box = SKSpriteNode()
override func didMove(to view: SKView) {
box.texture = SKTexture(imageNamed: "box")
box.size = CGSize(width: 50, height: 50)
box.position = CGPoint(x: 200, y: 200)
addChild(box)
let boxRandom = SKAction.run({
let boxPosition = Double.random(in: 300...500)
let boxMove = SKAction.move(to: CGPoint(x: 200, y: boxPosition), duration: 2)
self.box.run(boxMove)
})
let boxMove = SKAction.move(to: CGPoint(x: 200, y: 100), duration: 2)
let boxGroup = SKAction.sequence([boxMove, boxRandom])
let boxRepeat = SKAction.repeatForever(boxGroup)
box.run(boxRepeat)
}
}
Any suggestion? Thanks for all the answers in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SKAction.run
是即时发生的,因此它不会等待其中的SKAction.move
完成。对代码的一个简单修复是添加一个
SKAction.wait
,其持续时间与块内的SKAction.move
相同:如果您需要使用为每个移动操作自定义持续时间,您可以创建一个方法来运行随机移动并在移动完成时递归调用相同的方法。像这样的事情:
还可以考虑查看驱动游戏逻辑以更好地控制您的结果。
The
SKAction.run
takes place instantaneously, so it won't wait for the completion of theSKAction.move
inside it.A simple fix for your code would be to add an
SKAction.wait
for the same duration as theSKAction.move
inside the block to the sequence:If you need to use a custom duration for each move action, you could create a method that will run the random move and recursively call the same method when the move completes. Something like this:
Also consider looking at Drive Game Logic for more control over your outcomes.