将UIView的位置翻译为SKScene

时间:2017-03-23 12:52:12

标签: ios swift sprite-kit

我想在我的UIView中使用touchBegan功能,我应该触发SKScene方法。一切都在工作,期待我的SKNode的startingPosition与UIView中的触摸不同。我在这里阅读:Confusing reversed touch event in Swift但是他们没有给出解决方法如何将UIView触摸手势转换为与触摸位置相对应的SKScene触摸手势。这有效:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
    var currentPoint = touch.location(in: scene)
    executeSpawningStar(startPosition: currentPoint)
    }
}

但我在它上面放了一个UIView,这个功能不再起作用了。当我把它更改为:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
    var currentPoint = touch.location(in: newUIView)
    executeSpawningStar(startPosition: currentPoint)
    }
}

产卵看起来很奇怪。产卵星的协调不正确。如何将正确的坐标从UIView传输到SpriteKit设置以匹配触摸手势的实际位置?

1 个答案:

答案 0 :(得分:3)

好消息! SKView具有与SKScene坐标进行转换的方法。

func convert(_ point: CGPoint, from scene: SKScene) -> CGPoint
func convert(_ point: CGPoint, to scene: SKScene) -> CGPoint

所以你可以这样做:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        var currentPoint = touch.location(in: newUIView)
        currentPoint = gameScene.convertPoint(fromView: currentPoint)
        executeSpawningStar(startPosition: currentPoint)
    }
}

https://developer.apple.com/reference/spritekit/skview/1520328-convert https://developer.apple.com/reference/spritekit/skview/1519847-convert