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

我有一个自定义类,它是一个SKNode,它又有几个SKSpriteNodes。 有没有一种方法可以检测到我的游戏场景中的这些小孩SKSpriteNodes?

我正在迅速工作

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

检查苹果的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") } } 

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

您需要比较Touch的位置和您的SKNode的位置

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

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