我真的很沮丧,我已经试着让它工作了将近两天了:(
如何在swift中将click事件添加到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”的函数时发生,我该如何实现它?
非常感谢您的帮助:)

最佳答案

给你的SKSpriteNode起个名字,这样我们就可以在SKScene的touchesStarted或touchesEnd方法中识别它。
同时将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

07-27 20:21