我已经在Swift中编程了大约四个月,现在使用Sprite Kit为IOS构建一些简单的Arcade游戏。直到最近,我还没有遇到识别特定节点中的触摸的任何问题。在我的一个项目的主屏幕中,我添加了另一个SKLabelNode,用于应用程序的最新添加,遵循与其他项目相同的实现布局,但是这个不起作用。当标签被点击时,它应该运行一个函数但是甚至没有那么远,我想出了使用断点。这是所有相关的代码,请看看,我已经过了这四个小时,它一直让我发疯。
import SpriteKit
let twistedLabelName = "twisted"
class StartScene: SKScene {
var play1P = SKLabelNode(fontNamed: "HelveticaNeue-Thin")
var play2P = SKLabelNode(fontNamed: "HelveticaNeue-Thin")
var playTwisted = SKLabelNode(fontNamed: "HelveticaNeue-Thin")
override func didMoveToView(view: SKView) {
initializeValues()
self.userInteractionEnabled = true
}
func initializeValues () {
backgroundColor = UIColor.whiteColor()
play1P.name = "1p"
play1P.text = "Play 1P"
play1P.fontColor = SKColor.blackColor()
play1P.fontSize = 40
play1P.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetHeight(self.frame) * 0.8)
play1P.zPosition = 100
self.addChild(play1P)
play2P.name = "2p"
play2P.text = "Play 2P"
play2P.fontColor = SKColor.blackColor()
play2P.fontSize = 40
play2P.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetHeight(self.frame) * 0.6)
play2P.zPosition = 100
self.addChild(play2P)
playTwisted.text = "Twisted"
playTwisted.fontColor = SKColor.blackColor()
playTwisted.name = twistedLabelName
playTwisted.fontSize = 40
playTwisted.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetHeight(self.frame) * 0.4)
self.addChild(playTwisted)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch in touches {
let location = touch.locationInNode(self)
if let theName = self.nodeAtPoint(location).name {
if theName == "1p" {
// Some function
}
else if theName == "2p" {
// Some function
}
else if theName == twistedLabelName {
// This is the one that doesn't work
// Some function
}
}
}
}
}
答案 0 :(得分:2)
请注意,您可以扩展任何SKNode(包括SKLabelNode)并处理子类中的触摸。首先设置isUserInteractionEnabled = true。例如
import SpriteKit
class MyLabelNode: SKLabelNode {
override init() {
super.init()
isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
isUserInteractionEnabled = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print( #file + #function )
}
}