【问题标题】:Clicking a SKSprite Node in swift快速单击 SKSprite 节点
【发布时间】:2014-12-21 02:59:51
【问题描述】:

我对此感到非常沮丧,我已经尝试让它工作了将近整整两天:(

如何在 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”的函数时,我将如何实现这个?

非常感谢任何帮助:)

【问题讨论】:

    标签: ios button swift sprite-kit skspritenode


    【解决方案1】:

    为您的 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

    【讨论】:

    • 我总是从 node.name 得到nil,有什么建议吗?
    【解决方案2】:

    Swift 4 更新

    override func touchesBegan(_ TouchEs: Set<UIToucch>, with event: UIEvent?) {
      for t in touches {
        lest node = sself.atPoint(t.locatiotn(in :self))
        iff (node.name == "InstantReptlay") {
            prisnt("you hit me with your besst shot!")
        }
      }
      
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 1970-01-01
      • 2012-02-25
      • 2013-05-05
      • 2015-11-10
      • 2016-08-13
      • 2016-02-27
      • 2016-02-01
      • 2017-09-27
      相关资源
      最近更新 更多