如何拖动SKSpriteNode而不用Swift触摸它

时间:2015-08-10 20:14:16

标签: swift sprite-kit uipangesturerecognizer

我试图通过拖动水平移动SKSpriteNode。为了了解我尝试实现的目标,您可以watch this。我希望玩家能够在不触碰精灵的情况下拖动精灵。但我真的不知道如何正确实施它。 我试着做类似的事情:

 override func didMoveToView(view: SKView) {
    /* Setup your scene here */

    capLeft.size = self.capLeft.size
    self.capLeft.position = CGPointMake(CGRectGetMinX(self.frame) + self.capLeft.size.height * 2, CGRectGetMinY(self.frame) + self.capLeft.size.height * 1.5)
    capLeft.zPosition = 1

    self.addChild(capLeft)

    let panLeftCap: UIPanGestureRecognizer = UIPanGestureRecognizer(target: capLeft, action: Selector("moveLeftCap:"))

当我设置moveLeftCap函数时,我为UIPanGestureRecognizer找到的代码需要"查看"并给我一个错误。我还想限制它不应该通过的精灵的最小和最大位置。   任何想法如何实现?

1 个答案:

答案 0 :(得分:2)

您可能会收到该错误,因为您无法从树中的任何节点访问该视图。您可以将其称为场景!.view或您在场景中处理手势,如果您想要保持简单,这是更好的。

我试了一下,想出了这个基本场景:

import SpriteKit

class GameScene: SKScene {

    var shape:SKNode!

    override func didMoveToView(view: SKView) {
        //creates the shape to be moved
        shape = SKShapeNode(circleOfRadius: 30.0)
        shape.position = CGPointMake(frame.midX, frame.midY)
        addChild(shape)

        //sets up gesture recognizer
        let pan = UIPanGestureRecognizer(target: self, action: "panned:")
        view.addGestureRecognizer(pan)
    }

    var previousTranslateX:CGFloat = 0.0

    func panned (sender:UIPanGestureRecognizer) {
        //retrieve pan movement along the x-axis of the view since the gesture began
        let currentTranslateX = sender.translationInView(view!).x

        //calculate translation since last measurement
        let translateX = currentTranslateX - previousTranslateX

        //move shape within frame boundaries
        let newShapeX = shape.position.x + translateX
        if newShapeX < frame.maxX && newShapeX > frame.minX {
            shape.position = CGPointMake(shape.position.x + translateX, shape.position.y)
        }

        //(re-)set previous measurement
        if sender.state == .Ended {
        previousTranslateX = 0
        } else {
            previousTranslateX = currentTranslateX
        }
    }
}

当您在屏幕上移动手指时,圆圈会相应地沿x轴移动。

如果你想在x和y方向上移动精灵,记得要从视图中反转y值(在视图中向上是在场景中向下)。