Quick stop of SKAction.repeatForever function inside function?

I am trying to stop my background from colliding.

This is what creates and moves the background:

 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


    }

      

How to stop bg.run (moveBGForever? I tried bg.removeAllActions () and also tried to add it to the key, but it doesn't do anything.

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



}

      

+3


source to share


2 answers


This is because you shouldn't create a loop while

to repeat the action, but you should just create a:

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)

      



In your case, you can repeat this action 3 times. After that, you can start or stop this actionRepeated

one by giving it a key when you need to stop it.

+4


source


You will probably need to rebuild your code. Instead of using a "while" loop:

while i < 3 {
...
}

      



you have to use .repeat(yourBgActions, count:3)

.

+1


source







All Articles