【问题标题】:TouchEvents in watchOS 3 SpriteKit?watchOS 3 SpriteKit 中的触摸事件?
【发布时间】:2016-11-03 09:06:56
【问题描述】:

在 watchOS 3 中使用 SpriteKit 时,如何处理触摸事件?我正在从 iOS 移植 SpriteKit 游戏,下面的代码将不起作用。或者你必须以某种方式控制 WKInterfaceController?

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

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

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

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

【问题讨论】:

    标签: sprite-kit watchkit watchos-3


    【解决方案1】:

    在对同样的问题感到非常沮丧之后,我最终使用了手势识别器,并从那里计算了位置。

    @IBAction func handleSingleTap(tapGesture: WKTapGestureRecognizer) {
        let location = tapGesture.locationInObject()
        if yourSpriteNodeRect.contains(location) {
            //do stuff
        }
    }
    

    一个提示:虽然我在创建处理手势识别器的方法时发现了一个奇怪的错误,即默认情况下手势没有传递到方法中。我必须按 ctrl + 拖动来创建方法,然后修改签名以包含手势。如果我使用签名中的手势创建方法,Xcode 将不允许我将手势识别器附加到它。

    似乎有更好的方法来检测触摸,但这是我目前找到的解决方法。

    【讨论】:

    • 你可以做我修改签名的事情,或者你可以保留它并添加一个保护声明:@IBAction func panRecognized(_ sender: AnyObject) { guard let panGesture = sender as? WKPanGestureRecognizer else { return }
    • 是的,但文档 (developer.apple.com/reference/watchkit/wkgesturerecognizer) 允许两种类型的签名。警卫声明应该是必要的。 IBAction func handleGesture() / IBAction func handleGesture(gestureRecognizer : WKKestureRecognizer)
    • 识别器给触摸添加延迟是很烦人的。取决于游戏类型
    【解决方案2】:

    要获得接近触地事件的内容,请使用具有超短持续时间 (0.001) 的 WKLongPressGestureRecognizer。连接到此识别器的 IBAction 将立即获得着陆事件。该位置位于识别器的 locationInObject 属性中。如果目标是获得移动触摸,则使用平移识别器。

    【讨论】:

    • 它的持续时间和移动也为 0。
    【解决方案3】:

    为此,我首先在手表故事板中连接了一个手势识别器。创建了一个IBAction,然后在传入gesture.locationInObject() 的SpriteKit 场景上调用一个方法。然后在转换的场景方法中,这里有一些代码。

    let screenBounds = WKInterfaceDevice.current().screenBounds
    let newX = ((location.x / screenBounds.width) * self.size.width) - (self.size.width / 2)
    let newY = -(((location.y / screenBounds.height) * self.size.height) - (self.size.height / 2))
    

    newX 和 newY 是场景中的触摸坐标。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      相关资源
      最近更新 更多