缓解SKSpriteNode的动画

时间:2015-11-15 15:06:55

标签: ios swift sprite-kit

我使用touchesMoved方法移动精灵。到目前为止,这工作正常,但结果看起来有点不自然。一旦我的手指移动停止,精灵立即停止。如果精灵用一个缓出功能连续运动一点时间,那么会产生更自然的印象。知道如何实现这个吗?

这是我的代码:

import SpriteKit

class GameScene: SKScene {

    var sprite: SKSpriteNode?
    var xOrgPosition: CGFloat = 0.0

    override func didMoveToView(view: SKView) {
        sprite = SKSpriteNode(imageNamed:"Spaceship")
        sprite!.xScale = 0.1
        sprite!.yScale = 0.1
        sprite!.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
        self.addChild(sprite!)
    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

        for touch in touches {
            let xTouchPosition = touch.locationInNode(self).x
            if xOrgPosition != 0.0 {

                // calculate the new position
                sprite!.position = CGPoint(x: sprite!.position.x - (xOrgPosition - xTouchPosition), y: sprite!.position.y)
            }

            // Store the current touch position to calculate the delta in the next iteration
            xOrgPosition = xTouchPosition
        }
    }



   override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // Reset value for the next swipe gesture
        xOrgPosition = 0
   }
}

更新: 我根据hamobi的答案做了一个简短的示例项目

Tutorial
Git repository

1 个答案:

答案 0 :(得分:3)

我认为这可能就是你想要的。如果您有任何问题,请告诉我们。)

import SpriteKit

class GameScene: SKScene {

    var sprite: SKSpriteNode?
    var xOrgPosition: CGFloat?

    override func didMoveToView(view: SKView) {
        sprite = SKSpriteNode(imageNamed:"Spaceship")
        sprite!.xScale = 0.1
        sprite!.yScale = 0.1
        sprite!.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
        self.addChild(sprite!)
    }


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

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        xOrgPosition = nil
    }


    override func update(currentTime: NSTimeInterval) {
        if let xPos = xOrgPosition {
            sprite!.position.x += (xPos - sprite!.position.x) * 0.1
        }
    }
}