我真的很沮丧,现在我已经尝试让它工作将近整整两天:(
如何在 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”的函数,我将如何实现它?
非常感谢任何帮助:)
最佳答案
为您的 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 一致。
关于ios - 快速点击一个 SKSprite 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26562036/