我一直试图制作一个永远运行的SKAction,我可以随时停止.我这样做了:
override func didMove(to view: SKView) {
run(SKAction.repeatForever (
SKAction.sequence ([
SKAction.run(drawFrame),SKAction.wait(forDuration: 0.01),])),withKey: "frameDrawing"
)
}
然后在drawFrame函数中我像这样停止SKAction:
func drawFrame() {
//(code)
if stop {
removeAction(forKey: "frameDrawing")
}
}
出于某种原因,SKAction仅在停止变为真后运行3或4次后停止.我希望它在stop设置为true时立即停止,而不是在重复3或4次后立即停止.
如果有人知道如何解决这个问题,请告诉我,因为我尝试了很多东西,他们从来没有解决过这个问题.谢谢!
编辑:这是我的代码:
var drawingFrame = SKAction()
class GameScene: SKScene,SKPhysicsContactDelegate {
override func didMove(to view: SKView) {
drawingFrame = SKAction.repeatForever (
SKAction.sequence ([
SKAction.run(drawFrame),SKAction.wait(forDuration: 0.03),]))
run(drawingFrame)
}
func drawFrame() {
//(code)
if stop {
drawingFrame.speed = 0.0
}
}
如果您想知道为什么我在开始时将SKAction drawingFrame设置为空SKAction,那是因为我需要在两个函数之前定义SKAction.否则,两个函数都没有定义.
编辑任何有相同问题的人:我已经使用自己的想法和@ appzYourLife的解决方案解决了问题.每次都有效的最有效方法是只在stop等于false时才运行代码.但是,请确保停止程序的if语句超出该括号,以便SKAction最终停止.这是工作代码:
var drawingFrame = SKAction()
class GameScene: SKScene,]))
run(drawingFrame)
}
func drawFrame() {
if stop = false {
//(code)
}
if stop {
removeAllActions()
}
}
如果您愿意,可以对stop = false语句使用if else语句.
我没有确切的解释为什么drawFrame()目前被多次调用(但我会尝试发现:D)……无论如何,试试这段代码:
import SpriteKit
class GameScene: SKScene,SKPhysicsContactDelegate {
var stop = false
override func didMove(to view: SKView) {
run(SKAction.repeatForever (
SKAction.sequence ([
SKAction.run({[uNowned self] in
if self.stop {
self.action(forKey: "frameDrawing")?.speed = 0.0
}else{
self.drawFrame()
}
}),SKAction.wait(forDuration:0.03),withKey: "frameDrawing"
)
}
func drawFrame() {
//(code)
print("drawFrame")
}
override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
super.touchesBegan(touches,with: event)
stop = !stop
print(stop ? "stopped": "running")
if !stop {
self.action(forKey: "frameDrawing")?.speed = 1.0
}
}
}
使用touchesBegan切换暂停模式.