swift - 如何在 Swift 3.0 中拖放 Sprite ?

标签 swift sprite-kit sprite swift3

我想要做的就是能够在屏幕上拖放 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/

相关文章:

ios - Swift - 广告只是应用程序上的一个白条

iOS 回合制匹配,推送通知不起作用,GKTurnBasedEventListener 函数未调用

objective-c - 界面生成器 + Sprite 条

ios - 当手指经过时,Swift Button 的作用就像一个传感器

ios - 为特定 UITextField 分配字符限制

swift - 如何在spritekit中检测双击

swift - 如何为我的场景添加背景? SpriteKit swift 4

swift - 如何为 gamescene.sks 中添加的节点定义自己的物理体

CSS 列表 Sprite 对齐

flutter - 有没有办法在 Flutter 中将 Text 与 spritewidget 一起使用?