在SpriteKit中检测对象的子节点上的触摸

时间:2014-10-12 19:06:54

标签: ios xcode swift touch sprite-kit

我有一个自定义类,它是一个SKNode,其中包含几个SKSpriteNodes。有没有办法可以从我的游戏场景中检测这些孩子SKSpriteNodes的触摸?

我正在快速工作

3 个答案:

答案 0 :(得分:10)

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {

   let touch = touches.anyObject() as UITouch

   let touchLocation = touch.locationInNode(self)

    if([yourSprite containsPoint: touchLocation])
    {
         //sprite contains touch
    }
}

来源:http://www.raywenderlich.com/84434/sprite-kit-swift-tutorial-beginners

答案 1 :(得分:2)

检查Apple的SceneKitVehicle演示。有人ported it to Swift

您想要的代码位于GameView.swift文件中。在GameView中,您将看到touchesBegan覆盖。这是我对Swift 2.1的版本:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    guard let scene = self.overlaySKScene else {
        return
    }

    let touch = touches.first!
    let viewTouchLocation = touch.locationInView(self)
    let sceneTouchPoint = scene .convertPointFromView(viewTouchLocation)
    let touchedNode = scene.nodeAtPoint(sceneTouchPoint)

    if (touchedNode.name == "Play") {
        print("play")
    }
}

如果不清楚;通过Storyboard将GameView设置为应用程序的视图类。

答案 2 :(得分:0)

您需要将Touch的位置与SKNode的位置进行比较

您可以使用locationInNode()通过以下方法之一获取触摸位置:

  • 的touchesBegan()
  • touchesMoved()
  • touchesEnded()
相关问题