当我的heroNode与Swift Spritekit中的敌人节点联系时,我如何暂停我的背景?

时间:2023-01-16 16:15:33

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?

当我的英雄节点与敌人接触时,我正试图暂停我的背景。当我使用这个代码时,我在下面张贴了背景的速度并没有停止它保持正常速度。我尝试仅在全球范围内声明“城市”,但我收到一条错误消息称尝试添加已有父母的SKNode。我究竟做错了什么?

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!!!")

    }
}

1 个解决方案

#1


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:

第一个问题是,您声明了一个类变量city,但在您的add方法中,您不使用类变量而是使用自己的city变量。所以你应该删除该类变量:

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()

#1


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:

第一个问题是,您声明了一个类变量city,但在您的add方法中,您不使用类变量而是使用自己的city变量。所以你应该删除该类变量:

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()