我想要做的就是能够在屏幕上拖放 Sprite 。我尝试了以下代码:
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
}
}
}
这段代码确实有效,但是,当我非常快地拖动球时,我猜它检测到“球”不再包含点“位置”并且球停止了,这意味着我又把球捡起来了。我希望球能够快速响应我的触摸,这样球就不会停止移动。我该怎么做?
最佳答案
这是在 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
}
}
关于swift - 如何在 Swift 3.0 中拖放 Sprite ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39004565/