SpriteKit - Mouse Snaps to Center On Sprite Drag

吃可爱长大的小学妹 提交于 2019-12-06 14:51:04

It's fairly straightforward to drag a sprite from the touch location instead of from the center of the sprite. To do this, calculate and store the difference (i.e., offset) between the touch location and the center of the sprite. Then, in touchesMoved, set the sprite's new position to the touch location plus the offset.

You can optionally overload the + and - operators to simplify adding and subtracting CGPoints. Define this outside of the 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)
}

In GameScene, define the following instance variable

var offset:CGPoint?

and then in touchesBegan, replace

touchedNode.position = location

with

offset = location - touchedNode.position

and in touchesMoved, replace

touchedNode.position = location

with

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

I generalized the solution to offset the sprite's position in both the x and y dimensions. In your app, you can simply offset the sprite's y position since x is ignored.

Whirlwind

You don't need touchesBegan and touchesEnded for this. You can use just 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)


        }
    }

The idea is to calculate translation. You can read more about this solution here. For future readers Obj-C solution on StackOverflow can be found on this link.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!