I'm trying to make a pause button and a play button for my game, but I don't know what happens that the screen just freezes when I touch pause button (play button appears and remove pause button) and then touch play button (freeze).
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//Pause
pauseButton = SKSpriteNode (imageNamed: "pause")
pauseButton.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
self.addChild(pauseButton)
//Play
playButton = SKSpriteNode (imageNamed: "play")
playButton.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
//when touch buttons
let touch = touches.first!
if pauseButton.containsPoint(touch.locationInNode(self)) {
addChild(playButton)
pauseButton.removeFromParent()
}
if playButton.containsPoint(touch.locationInNode(self)) {
addChild(pauseButton)
playButton.removeFromParent()
}
}
答案 0 :(得分:2)
触摸屏幕时创建按钮是没有意义的。这意味着每次触摸屏幕时都会创建一个新按钮。 移动上面的所有代码&#34; //触摸按钮&#34; out of touches方法并将其放入didMoveToView
您的代码结构可能看起来像这样
class GameScene: SKScene {
var pauseButton: SKSpriteNode! // to make your code even safer you could use optionals here
var playButton: SKSpriteNode! // to make your code even safer you could use optionals here
override func didMoveToView(view: SKView) {
//Pause
pauseButton = SKSpriteNode (imageNamed: "pause")
pauseButton.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
self.addChild(pauseButton)
//Play
playButton = SKSpriteNode (imageNamed: "play")
playButton.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
let node = nodeAtPoint(location)
//when touch buttons
if node == pauseButton {
addChild(playButton)
pauseButton.removeFromParent()
}
if node == playButton {
addChild(pauseButton)
playButton.removeFromParent()
}
}
}
}
或者您也可以将所有按钮添加到场景中,例如隐藏pauseButton。而不是删除和添加按钮,你只需隐藏和取消隐藏它们
pauseButton.hidden = true
只有当你的目标是ios 9或更高版本且隐藏节点不再接收触摸事件时,这才能正常工作。
希望这有帮助