我正在尝试为我的游戏制作一个暂停按钮和一个播放按钮,但我不知道当我点击暂停按钮(播放按钮出现并移除暂停按钮),然后点击播放按钮(冻结)时,屏幕就会冻结。
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()
}
}发布于 2016-04-04 20:54:59
当你触摸屏幕时创建按钮是没有意义的。这意味着你每次触摸屏幕时都会创建一个新的按钮。将“//时间触摸按钮”上面的所有代码移出touch方法,并将其放在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或以上,隐藏节点不再接收触摸事件时,这才能正常工作。
希望这能有所帮助
https://stackoverflow.com/questions/36410673
复制相似问题