繁体   English   中英

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

[英]Detect touch on child node of object in SpriteKit

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

我在swift工作

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

检查Apple的SceneKitVehicle演示。 有人把它移植到斯威夫特

您想要的代码在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设置为应用程序的视图类。

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

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

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

Swift 5+

如果希望将触摸逻辑封装在一个节点中,在本地处理,只需在相应的节点中将interaction设置为true即可。

isUserInteractionEnabled = true

然后,当然,根据您的需要覆盖 touchesBegan。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {}

如果您仍然希望在子节点内部发生触摸时在场景中接收触摸,例如,您可以为子节点的delegate定义一个协议和属性,并将场景设置为它。

例如:

final class GameScene: SKScene {
    private let childNode = ChildNode()

    override func didMove(to view: SKView) {
        addChild(childNode)
        childNode.delegate = self
    }
}

extension GameScene: TouchDelegate {}

protocol TouchDelegate {
    func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
}

final class ChildNode: SKSpriteNode {
    var delegate: TouchDelegate?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        delegate?.touchesBegan(touches, with: event)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM