【问题标题】:How can I move sprites around with my finger?如何用手指移动精灵?
【发布时间】:2015-05-25 00:12:41
【问题描述】:

我希望能够用手指移动精灵。我首先有一个变量来判断手指是否在精灵上:

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
}

【问题讨论】:

标签: ios swift sprite-kit


【解决方案1】:

您可以像这样修改函数来跟踪触摸。

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    相关资源
    最近更新 更多