【问题标题】:Dragging an SKSpriteNode only when touched仅在触摸时拖动 SKSpriteNode
【发布时间】:2015-10-11 07:34:45
【问题描述】:

我有一个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 {

        }
    }
}

【问题讨论】:

标签: ios swift sprite-kit swift2 skspritenode


【解决方案1】:

您可以实现这三种方法来实现您想要的: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
}

【讨论】:

  • 谢谢。工作完美。你能指出我的方向,知道为什么我的间歇性工作吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多