我真的很沮丧,我一直试图让它工作近两整天:(
如何在swift
中向SKSpriteNode添加点击事件 let InstantReplay:SKSpriteNode = SKSpriteNode(imageNamed: "InstantReplay")
InstantReplay.position = CGPoint(x: size.width + InstantReplay.size.width/2, y: size.height/2)
InstantReplay.size = CGSize(width: size.width/1.4, height: size.height/8)
addChild(InstantReplay)
InstantReplay.runAction(SKAction.moveToX(size.width/2, duration: NSTimeInterval(1)))
我想要发生的是当点击“InstantReplay”以运行名为“InstantReplay_Clicked”的功能时,我将如何实现这一目标?
任何帮助非常感谢:)
答案 0 :(得分:3)
为您的SKSpriteNode命名,以便我们可以在您的SKScene的touchesBegan或touchesEnded方法中识别它。
同时将SKSpriteNode的userInteractionEnabled设置为false,这样它就不会为自己捕获触摸事件,也不会将它们传递给场景。
override init() {
super.init()
let instantReplay = SKSpriteNode(imageNamed: "InstantReplay")
instantReplay.position = CGPoint(x: size.width + instantReplay.size.width/2, y: size.height/2)
instantReplay.size = CGSize(width: size.width/1.4, height: size.height/8)
instantReplay.name = "InstantReplay"; // set the name for your sprite
instantReplay.userInteractionEnabled = false; // userInteractionEnabled should be disabled
self.addChild(instantReplay)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let location = touches.anyObject()?.locationInNode(self)
let node = self.nodeAtPoint(location!)
if (node.name == "InstantReplay") {
println("you hit me with your best shot!")
}
}
(哦 - 我还将你的instantReplay变量重命名为使用lowerCamelCase,与Swift best practices一致。
答案 1 :(得分:0)
迅速4更新
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
let node = self.atPoint(t.location(in :self))
if (node.name == "InstantReplay") {
print("you hit me with your best shot!")
}
}
}