ios - 快速点击一个 SKSprite 节点

标签 ios button swift sprite-kit skspritenode

我真的很沮丧,现在我已经尝试让它工作将近整整两天:(

如何在 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/

相关文章:

ios - Firebase 动态链接无法在 iOS 10 上打开应用程序

ios - 如何自定义 UITableView 的 Separator View?

Swift - 从 ISO8601 日期字符串中检索时区

ios - 按其 Double 参数之一对对象数组进行排序

html - 按钮文本更改时保持按钮大小稳定

ios - 如何将 SecIdentityRef 添加到 iOS 钥匙串(keychain),swift

ios - 收到内存警告。 Level=1 - 具有 5 个选项卡的 UITabBarController 应用程序

ios - 如何使用 Monotouch 获取行高?

html - 如何使用 flexbox 在中心底部对齐元素

javascript - 在按钮点击 block 上调用 JS 函数 CSS :hover