仅在触摸时拖动SKSpriteNode

时间:2015-10-11 07:34:46

标签: ios swift sprite-kit swift2 skspritenode

我有SKSpriteNode我希望通过touchesMoved在屏幕上拖动。但是,如果触摸没有首先出现在精灵的位置(不跳过场景),我不希望精灵移动。

我有一个间歇性的解决方案但是相信某些东西更优雅,更实用,因为这个解决方案无法正常工作 - 如果用户没有跟上触摸位置,就好像精灵位置一样快速拖动精灵。

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

        var touchPoint : CGPoint = location
        var muncherRect = muncherMan.frame
        if (CGRectContainsPoint(muncherRect, touchPoint)) {
            muncherMan.position = location
        } else {

        }
    }
}

1 个答案:

答案 0 :(得分:2)

您可以实现这三种方法来实现您的目标:touchesBegantouchesMovedtouchesEnded。触摸muncherMan后,将muncherManTouched设置为true,表示muncherMan可能会在下一帧中移动。完成移动或触摸时,将muncherManTouched设置为false并等待下一次触摸。

这是示例代码。我为muncherMan添加了一个名称,以便我们可以确定touchesBegan中要触摸的节点。

var muncherManTouched = false
override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    ...
    muncherMan.name = "muncherMan"
    self.addChild(muncherMan)
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    /* Called when a touch begins */ 
    for touch in touches {
        let location = touch.locationInNode(self)
        let nodeTouched = self.nodeAtPoint(location)
        if (nodeTouched.name == "muncherMan") {
            muncherManTouched = true
        }
    }
}

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

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    muncherManTouched = false
}
相关问题