Swift 在函数中停止 SKAction.repeatForever?

Swift stop an SKAction.repeatForever within a function?

我试图阻止我的背景在碰撞时移动。

这就是创建和移动背景的原因:

 let bgTexture = SKTexture(imageNamed: "bg.png")
    let moveBGanimation = SKAction.move(by: CGVector(dx: 0, dy: -bgTexture.size().height), duration: 4)
    let shiftBGAnimation = SKAction.move(by: CGVector(dx: 0, dy: bgTexture.size().height), duration: 0)
    let moveBGForever = SKAction.repeatForever(SKAction.sequence([moveBGanimation, shiftBGAnimation]))

    var i: CGFloat = 0

    while i < 3 {

        bg = SKSpriteNode(texture: bgTexture)
        bg.position = CGPoint(x: self.frame.midX, y: bgTexture.size().height * i)
        bg.size.width = self.frame.width
        bg.zPosition = -2

        bg.run(moveBGForever)
        self.addChild(bg)

        i += 1


    }

我怎样才能停止 bg.run(moveBGForever?我试过 bg.removeAllActions() 也试过将它添加到密钥中,但这没有任何作用。

if contact.bodyA.categoryBitMask == ColliderType.object.rawValue || contact.bodyB.categoryBitMask == ColliderType.object.rawValue {



}

发生这种情况是因为您不应该创建一个 while 循环来重复一个动作,而您必须简单地创建一个:

let myCode = SKAction.run{
    bg = SKSpriteNode(texture: bgTexture)
    bg.position = CGPoint(x: self.frame.midX, y: bgTexture.size().height * i)
    bg.size.width = self.frame.width
    bg.zPosition = -2
    ...
}
let actionRepeated = SKAction.repeat(mycode,count:3)

在你的情况下,你可以重复这个动作3次。 之后,您可以 运行 或停止此 actionRepeated 给它一个密钥,只要您需要停止它。

您可能需要重构您的代码。而不是使用你的 'while' 周期:

while i < 3 {
...
}

你应该使用 .repeat(yourBgActions, count:3).