如何在Swift 3.0中拖放精灵?

时间:2016-08-17 19:15:25

标签: swift sprite-kit sprite swift3

我试图做的就是能够在屏幕上拖放精灵。我尝试过以下代码:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch in (touches ) {
        let location = touch.locationInNode(self)
        if ball.containsPoint(location) {
            ball.position = location    
}
}
}

这段代码确实有效,但是当我快速拖动球时,我猜它会检测到&#34;球&#34;不再包含点&#34;位置&#34;球停了,这意味着我再次接球。我希望球能够快速响应我的触球,这样球就不会停止移动。我该怎么做?

2 个答案:

答案 0 :(得分:13)

这是在Sprite Kit中执行此操作的正确方法。就像我在评论中所说,你需要将移动节点分配给激活状态,在这种情况下,我使用一个名为movableNode的变量来激活状态。当您触摸球时,它会通过将其分配给movableNode来激活。然后当您拖动手指时,movableNode将随拖动一起移动。然后,一旦释放,您可以通过将movableNode设置为nil来进入停用状态。请注意,此代码仅适用于单点触控应用程序,如果要处理多点触控,则需要跟踪正在进行拖动的触摸。

var movableNode : SKNode?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let location = touch.locationInNode(self)
        if ball.containsPoint(location) {
            movableNode = ball
            movableNode!.position = location    
        }
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first where movableNode != nil {
        movableNode!.position = touch.locationInNode(self)
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first where movableNode != nil {
        movableNode!.position = touch.locationInNode(self)
        movableNode = nil
    }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        movableNode = nil
    }
}

答案 1 :(得分:-2)

我有一个实现,我已经将UIImageView子类化并称之为&#34; DraggableImage&#34;

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        originalPosition = self.center
    }

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let position = touch.location(in: self.superview)
            self.center = CGPoint(x: position.x, y: position.y)
        }
    }

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        self.center = originalPosition
    }