ios - WatchOS3中SKShapeNode添加手势

标签 ios swift sprite-kit watchkit

我可以在 SpriteKit 场景中添加手势。但无法向我在场景中的节点之一添加手势。

此外,touchesBegan 方法在 WatchKit 中不可用。所以在我的界面中添加了 gestureRecognizer 并将其传递到 SpriteKit 场景中。

但这导致将 panGesture 添加到整个场景而不是我的节点。

有没有办法只将手势添加到我的一个节点?

最佳答案

您永远不会向节点添加手势。

您只能向任何可以识别手势的东西添加手势。

在 UIKit 中,这些是 UIView

在 Watchkit 中,这些是 WKInterfaces

现在你想在 Watchkit 中做的是,当手势开始时,检测你是否正在触摸一个节点

您可以在 Watchkit 中通过使用 locationinObject 获取位置并通过以下操作将其转换为场景坐标系:

extension WKGestureRecognizer {
    var position : CGPoint
    {
        get
        {
            let location = locationInObject()
            let bounds = objectBounds()
            let dWidth = self.scene.size.width / bounds.size.width
            let dHeight = self.scene.size.height / bounds.size.height
            let x = (location.x * dWidth) - scene.width * scene.anchorPoint.x)
            let y = (bounds.maxY - location.y) * dHeight - (scene.height * scene.anchorPoint.y)
            return CGPoint(x:x, y:y)
        }
    }
}

这样做是获取您在界面中的位置,然后通过翻转 y 轴将其转换为场景,然后调整场景宽度与界面宽度的差异。

现在要使用它,您只要在识别器方法中调用它,并检查您正在触摸的节点是否是您的节点

func didPan(_ recognizer: WKPanGestureRecognizer) {
        switch(recognizer.state)
        {
            case .began:
                let scenePosition = recognizer.position
                let node = scene.atPoint(scenePosition)
                guard let node = shapeNode else {return}
                //allow pan, so make a note or something
            case //do other cases here
        }
}

关于ios - WatchOS3中SKShapeNode添加手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42501636/

相关文章:

ios - TableView 中的 UIImageView 在单击或设备旋转之前不显示

swift - 如何显示标签栏 Controller ?

Swift 使 sksprite 节点随时间移动得更快

ios - iOS 中的 Storyboard约束

python - 如何使用IOS访问在线mongoDB数据

ios - 'NSInternalInconsistencyException',原因 : 'cannot decode special type ' 14' on pre iOS 11 Devices

objective-c - 在 SpriteKit 中配置 SKScene 内容的正确位置在哪里?

ios - SKAction 序列是否真的等到 Action 结束?

ios - 使用 pickerView 填充多个部分 tableView

ios - Xcode 8 swift 3 : Modal presentation transitioning delegate not called