如何在需要时生成SKSpriteNode?

时间:2015-04-01 23:28:24

标签: ios swift sprite-kit

我的SpriteKit游戏中有几个SKSpriteNodes,例如暂停和游戏场景的背景和按钮。现在我正在didMoveToView中声明并添加它们并使用以下内容:

let pauseButton = SKSpriteNode(imageNamed: "pauseButton")
let pauseBackground = SKSpriteNode (imageNamed: "pauseBackground")
let resumeButton = SKSpriteNode (imageNamed: "resumeButton")

然后,我正在初始化它们:

self.pauseButton.anchorPoint = CGPointMake(0.5, 0.5)
self.pauseButton.position = CGPointMake(CGRectGetWidth(self.frame) - self.cookieSpot / 3, CGRectGetMaxY(self.frame) - self.cookieSpot / 3)
pauseButton.size = self.pauseButton.size
pauseButton.name = "pauseButton"
pauseButton.zPosition = 1000

pauseBackground.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
self.pauseBackground.hidden = true
self.pauseBackground.name = "pauseBackground"
self.pauseBackground.zPosition = +1
resumeButton.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMinY(self.frame) + self.resumeButton.size.height * 2 + self.resumeButton.size.height - self.resumeButton.size.height / 4)
self.resumeButton.hidden = true
self.resumeButton.name = "resumeButton"
self.resumeButton.zPosition = +1

然后添加它们:

self.addChild(pauseBackground)
self.addChild(resumeButton)
self.addChild(gameOverBackground)

当它不需要时以及当用户点击暂停按钮时我试图使用这样的东西:

for touch: AnyObject in touches {
    let location = touch.locationInNode(self)
       switch self.nodeAtPoint(location) {
case pauseButton:
        self.pauseBackground.hidden = false
        self.resumeButton.hidden = false
        self.scene?.view?.paused = true
case resumeButton:
        self.pauseBackground.hidden = true
        self.resumeButton.hidden = true
        self.scene?.view?.paused = false
        default:
        println("not good")

   }
}

这根本不适合我。我猜它们正在产卵,但它们是看不见的。如何在不需要时存储节点并在适当的时候生成节点?

1 个答案:

答案 0 :(得分:3)

添加节点是在runloop结束时完成的,你在此之前暂停了视图...我猜问题与此有关(测试它并得到相同的结果)。在Obj-C中,一个简单的解决方法是使用performSelector方法,如here所述。在Swift中,你应该使用像dispatch_after这样的东西,或者使用类似this的东西(使用NSTimer)。希望这个对你有帮助。这也不是一个明确的答案,可能还有更多针对同一问题的解决方案。

编辑:

我刚刚找到了可行solution(暂停在某个方法中移动):

func pauseGame()
   {
         self.scene?.view?.paused = true
   }

然后在touchesBegan中调用它

 self.runAction(SKAction.runBlock(self.pauseGame))

你的touchesBegan应该是这样的:

 override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)
            switch self.nodeAtPoint(location) {
            case pauseButton:
                self.pauseBackground.hidden = false
                self.resumeButton.hidden = false

               self.runAction(SKAction.runBlock(self.pauseGame))
            case resumeButton:
                self.pauseBackground.hidden = true
                self.resumeButton.hidden = true
                self.scene?.view?.paused = false
            default:
                println("not good")

            }
        }
    }