SpriteKit - 鼠标捕捉到 Sprite 拖动的中心

SpriteKit - Mouse Snaps to Center On Sprite Drag

我正在尝试创建一个 iOS 游戏并且我拥有它,以便在触摸和移动项目时拖动它。拖动鼠标时,鼠标会吸附到精灵的中心。我怎样才能做到这一点才不会发生?

Here 是正在发生的事情的一个例子。

这里是处理触摸输入的函数

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    var papers = 0

    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)
        let touchedNode = nodeAtPoint(location)

        if ((touchedNode.name?.contains("paper")) != nil) {

            touchedNode.position = location
            touchedNode.position.x = CGRectGetMidX(self.frame)
        }
    }
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)
            let touchedNode = nodeAtPoint(location)

            if ((touchedNode.name?.contains("paper")) != nil) {

                touchedNode.position = location
                touchedNode.position.x = CGRectGetMidX(self.frame)
            }
        }
    }

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        let touchedNode = nodeAtPoint(location)
        if ((touchedNode.name?.contains("paper")) != nil) {
            touchedNode.zPosition = 0
            touchedNode.position.x = CGRectGetMidX(self.frame)
        }
    }
}

P.S。 contains 是字符串 class 的扩展,用于检查子字符串是否在字符串中

提前致谢!

为此您不需要 touchesBegan 和 touchesEnded。您可以只使用 touchesMoved:

for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        let touchedNode = nodeAtPoint(location)
        let previousPosition = touch.previousLocationInNode(self)

        if (touchedNode.name == "paper") {

            var translation:CGPoint = CGPoint(x: location.x - previousPosition.x , y: location.y - previousPosition.y )

            touchedNode.position = CGPoint(x: touchedNode.position.x , y: touchedNode.position.y + translation.y)


        }
    }

思路是计算翻译。您可以阅读有关此解决方案的更多信息 here. For future readers Obj-C solution on Whosebug can be found on this link

从触摸位置而不是从 sprite 的中心拖动 sprite 相当简单。为此,计算并存储触摸位置和精灵中心之间的差异(即偏移量)。然后,在touchesMoved中,将精灵的新位置设置为触摸位置加上偏移量。

您可以选择性地重载 +- 运算符以简化加法和减法 CGPoint。在 GameScene 之外定义它 class:

func - (left:CGPoint,right:CGPoint) -> CGPoint {
    return CGPoint(x: right.x-left.x, y: right.y-left.y)
}

func + (left:CGPoint,right:CGPoint) -> CGPoint {
    return CGPoint(x: right.x+left.x, y: right.y+left.y)
}

在GameScene中,定义如下实例变量

var offset:CGPoint?

然后在touchesBegan中替换

touchedNode.position = location

offset = location - touchedNode.position

并在 touchesMoved 中替换

touchedNode.position = location

if let offset = self.offset {
    touchedNode.position = location + offset
}

我概括了在 xy 维度上偏移精灵位置的解决方案。在您的应用中,您可以简单地偏移精灵的 y 位置,因为 x 被忽略了。