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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26328886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:51:22  来源:igfitidea点击:

Detect touch on child node of object in SpriteKit

iosxcodeswifttouchsprite-kit

提问by Kyle Goslan

I have a custom class that is an SKNode, which in turn has several SKSpriteNodes in it. Is there a way I can detect touches on these child SKSpriteNodes from my game scene?

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

I'm working in swift

我正在快速工作

采纳答案by meisenman

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
    }
}

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

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

回答by Graham Perks

Examine Apple's SceneKitVehicledemo. Someone kindly ported it to Swift.

检查 Apple 的SceneKitVehicle演示。有人好心地将它移植到 Swift

The code you want is in the GameView.swift file. In the GameView you'll see the touchesBegan override. Here's my version of it for Swift 2.1:

您需要的代码在 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")
    }
}

If it's not clear; the GameView is set as the app's view class by way of the Storyboard.

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

回答by CorPruijs

You'll need to compare the location of your Touch to the location of your SKNode

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

You can get the location of your touch at one of the following methods, using locationInNode():

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

  • touchesBegan()
  • touchesMoved()
  • touchesEnded()
  • 触摸开始()
  • 触摸移动()
  • 触摸结束()