ios - SKShapeNode 拖动不流畅

标签 ios swift sprite-kit drag skshapenode

所以我是 swift 和 iOS 开发的 super 新手,但对编程来说并不是全新的,只是在学习一些教程,但基本上我的代码如下所示:

import SpriteKit


class GameScene: SKScene {


override func didMoveToView(view: SKView) {
    let circle = SKShapeNode(circleOfRadius: 30.0)
    circle.position = CGPointMake(100, 200)
    addChild(circle)
}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
    for touch in touches {
        let location = touch.locationInNode(self)
        let touchedNode = nodeAtPoint(location)
        touchedNode.position = location;
    }
}

当我构建它时,当我拖动它时它会识别并移动圆圈,但只有大约 30 像素,然后我必须再次触摸它才能移动它。我在这里做错了什么?

最佳答案

我可能是错的,但我相信您的手指正在离开节点限制并进入后台。我会这样设置:

// First make the shape available throughout the code and make sure you have a place to save the touch event for later use.
var circle: SKShapeNode!
var circleTouch: UITouch?

// Create the Shape
override func didMoveToView(view: SKView) {
    circle = SKShapeNode(circleOfRadius: 30.0)
    circle.position = CGPointMake(100, 200)
    addChild(circle)
}

// When a finger is placed on the screen, check if it's in the circle, if it is, keep that touch even in memory so we can reference it later because other fingers could touch other things in the scene.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    for touch in touches {
        if nodeAtPoint(touch.locationInNode(self)) == circle {
            circleTouch = touch as? UITouch
        }
    }
}

// Check if the touch event that is moving is the one that anchored the circle to our finger, if yes, move the circle to the position of the finger.
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
    for touch in touches {
        if circleTouch != nil {
            if touch as UITouch == circleTouch! {
                let location = touch.locationInNode(self)
                circle.position = location
            }
        }
    }
}

// Clean up the touch event when the finger anchoring the circle is raised from the screen.
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
    for touch in touches {
        if circleTouch != nil {
            if touch as UITouch == circleTouch! {
                circleTouch = nil
            }
        }
    }
}

您也可以在其中使用 if let 语句,但为了清晰起见,我检查了 nil

关于ios - SKShapeNode 拖动不流畅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28176324/

相关文章:

swift - 如何在异步迭代中设置DispatchGroup?

ios - 自定义表格 View 单元格不滑动

ios - iPhone 5 与 iPhone 4 的图像命名

ios - 无法加载从带有标识符的包中的 nib 引用的 ""图像

ios - Xcode 5 : Images disappear in storyboard when switching view between ios6 and ios7

ios - Adobe Air ios 打包程序

ios - 隐藏 mapView 上的蓝色用户位置

ios - 为什么这个应用程序从 Testflight 运行时会崩溃 100%,而从 Xcode 运行时可能会崩溃 10%

ios - 围绕原点旋转整个 SKView

iOS - 检索和保存游戏分数