【发布时间】:2014-12-07 08:42:06
【问题描述】:
我有一个自定义类,它是一个 SKNode,其中又包含几个 SKSpriteNode。有没有办法从我的游戏场景中检测到对这些子 SKSpriteNode 的触摸?
我正在快速工作
【问题讨论】:
标签: ios xcode swift touch sprite-kit
我有一个自定义类,它是一个 SKNode,其中又包含几个 SKSpriteNode。有没有办法从我的游戏场景中检测到对这些子 SKSpriteNode 的触摸?
我正在快速工作
【问题讨论】:
标签: ios xcode swift touch sprite-kit
查看 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")
}
}
如果不清楚; GameView 通过 Storyboard 设置为应用程序的视图类。
【讨论】:
您需要将 Touch 的位置与 SKNode 的位置进行比较
您可以使用 locationInNode() 通过以下方法之一获取您的触摸位置:
【讨论】:
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
【讨论】: