如何在spritekit中触摸相对于其原始位置的sprite

时间:2018-04-11 18:09:16

标签: swift sprite-kit sprite

我希望相对于玩家的触摸来移动精灵。我熟悉moveTo SKActions,但是我想知道如何实现sprite移动,其中sprite随着用户的触摸移动而移动。

例如,我在屏幕中央有一个精灵。如果我在屏幕底部触摸并向上移动手指,精灵将从中心(它的原始位置)向上移动。

谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个:

import SpriteKit

class GameScene: SKScene {

    var node = SKSpriteNode()
    var nodePosition = CGPoint()
    var startTouch = CGPoint()


    override func didMove(to view: SKView) {
        self.anchorPoint = CGPoint(x: 0.5, y: 0.5)

        // node set up
        node = SKSpriteNode(color: .red, size: CGSize(width: 50, height: 50))
        node.position = CGPoint.zero
        self.addChild(node)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let location = touch?.location(in: self){
            startTouch = location
            nodePosition = node.position
        }
    }
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let location = touch?.location(in: self){
            node.run(SKAction.move(to: CGPoint(x:  nodePosition.x + location.x - startTouch.x, y: nodePosition.y + location.y - startTouch.y), duration: 0.1))
        }
    }

}