1

I'm trying to pause my background when my hero node makes contact with the enemy. When I use this code I posted below the speed of the background doesn't stop it keeps going its normal speed. I tried declaring the "city" globally only but I get an error saying Attempted to add a SKNode which already has a parent. What am I doing wrong?

class GameScene: SKScene, SKPhysicsContactDelegate {    
    let city = SKSpriteNode(imageNamed: "skyline")
}

override func didMoveToView(view: SKView) {
    repeatCity()
}


func addCity() {
    let city = SKSpriteNode(imageNamed: "skyline")
    let moveToRight = SKAction.moveByX(-1000, y: 0, duration: 5.0)
    let repeatAction = SKAction.repeatActionForever(moveToRight)



    city.position = CGPointMake(self.size.width / 0.7, self.size.height / 1.9)
    city.zPosition = 13
    city.setScale(0.9)
    city.runAction(repeatAction)
    addChild(city)


}

func repeatCity() {
    let generateBlocks = SKAction.sequence([
        SKAction.runBlock(self.addCity),
        SKAction.waitForDuration(3.5)])
    let endlessAction = SKAction.repeatActionForever(generateBlocks)
    runAction(endlessAction)

}
    func didBeginContact(contact:SKPhysicsContact){

    if firstBody.categoryBitMask == HeroCategory && fourthBody.categoryBitMask == EnemyCategory {

        city.speed = 0
        theHero.physicsBody?.affectedByGravity = true
        println("contactwithEnemy!!!")

    }
}
Cesare
  • 9,139
  • 16
  • 78
  • 130
newtocoding
  • 109
  • 10

1 Answers1

0

The first problem is, that you declare a class variable city but in your add method you use not the class variable but an own city-variable. So you should remove that class variable:

let city = SKSpriteNode(imageNamed: "skyline")

Now at the moment, the action which you repeat for ever on your city node keeps running. To stop that action you should remove all actions from the city node at contact:

self.removeAllActions()
Christian
  • 22,585
  • 9
  • 80
  • 106