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


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

我在迅速工作


8099
2017-10-12 19:06


起源



答案:


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


10
2017-10-12 22:55





检查Apple的 SceneKitVehicle 演示。有人好心 将它移植到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设置为应用程序的视图类。


1
2017-10-15 15:49





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

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

  • 的touchesBegan()
  • touchesMoved()
  • touchesEnded()

0
2017-10-13 12:35



一些更详细的信息 - user3138007


答案:


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


10
2017-10-12 22:55





检查Apple的 SceneKitVehicle 演示。有人好心 将它移植到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设置为应用程序的视图类。


1
2017-10-15 15:49





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

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

  • 的touchesBegan()
  • touchesMoved()
  • touchesEnded()

0
2017-10-13 12:35



一些更详细的信息 - user3138007