如何用手指移动精灵?

时间:2015-02-10 15:57:25

标签: ios swift sprite-kit

我希望能够用手指移动精灵。我首先得到一个关于手指是否在精灵上的变量:

var isFingerOnGlow = false

然后我有touchesBegan函数,如果用户触摸精灵,我会改变上面变量的值:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    var touch = touches.anyObject() as UITouch!
    var touchLocation = touch.locationInNode(self)

    if let body = physicsWorld.bodyAtPoint(touchLocation) {
        if body.node!.name == GlowCategoryName {
            println("Began touch on hero")
            isFingerOnGlow = true
        }
    }
}

有时它有效,控制台显示“开始触摸英雄”,有时不显示。有没有更好的方法来编写第一部分?

然后我想知道touchesMoved的以下代码是否有效:

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
    if isFingerOnGlow{
        var touch = touches.anyObject() as UITouch!
        var touchLocation = touch.locationInNode(self)
        var previousLocation = touch.previousLocationInNode(self)

        var glow = SKSpriteNode(imageNamed: GlowCategoryName)

        // Calculate new position along x for glow
        var glowX = glow.position.x + (touchLocation.x - previousLocation.x)
        var glowY = glow.position.y + (touchLocation.y - previousLocation.y)

        // Limit x so that glow won't leave screen to left or right
        glowX = max(glowX, glow.size.width/2)
        glowX = min(glowX, size.width - glow.size.width/2)

        glow.position = CGPointMake(glowX, glowY)
    }
}

...

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
    isFingerOnGlow = false
}

1 个答案:

答案 0 :(得分:2)

您可以修改此类功能以跟踪触摸。

var isFingerOnGlow = false
var touchedGlowNode : SKNode!


override func touchesBegan(touches: NSSet, withEvent event:UIEvent) {
    var touch = touches.anyObject() as UITouch!
    var touchLocation = touch.locationInNode(self)

    let body = self.nodeAtPoint(touchLocation)
    if body.name == GlowCategoryName {
        println("Began touch on hero")
        touchedGlowNode = body
        isFingerOnGlow = true
    }

}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

    if isFingerOnGlow{

        let touch = touches.anyObject() as UITouch!
        let touchLocation = touch.locationInNode(self)
        let previousLocation = touch.previousLocationInNode(self)
        let distanceX = touchLocation.x - previousLocation.x
        let distanceY = touchLocation.y - previousLocation.y

        touchedGlowNode.position = CGPointMake(touchedGlowNode.position.x + distanceX,
            touchedGlowNode.position.y + distanceY)
    }
}

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
    isFingerOnGlow = false
}