如何正确设置SKSpriteNode子类的动画

Sam*_*Sam 1 animation sprite-kit swift

我设计了一个SKSpriteNode子类Ship,我想知道如何用几个不同的图像来动画它.我目前正在传递原始图片:

class Ship:SKSpriteNode{
    static var shipImage = SKTexture(imageNamed:"Sprites/fullShip.png")

        init(startPosition startPos:CGPoint, controllerVector:CGVector){
            super.init(texture: Ship.shipImage, color: UIColor.clearColor(), size: Ship.shipImage.size())
Run Code Online (Sandbox Code Playgroud)

但我不确定如何在之后循环播放图像地图集.我首先尝试在类中使用一个方法,然后在update函数中调用该方法:

func animateShip() {
    self.runAction(SKAction.repeatActionForever(
        SKAction.animateWithTextures(shipAnimationFrames,
            timePerFrame: 0.2,
            resize: false,
            restore: true)),
            withKey:"shipBlink")

        print("animate")
    }
Run Code Online (Sandbox Code Playgroud)

var shipAnimationFrames : [SKTexture]!在上面声明GameScene,这个块位于didMoveToView

    //Ship animation
    let shipAnimatedAtlas = SKTextureAtlas(named: "ShipImages")
    var blinkFrames = [SKTexture]()

    let numImages = shipAnimatedAtlas.textureNames.count
    for var i=1; i<=numImages; i += 1 {
        let shipTextureName = "samShip\(i).png"
        blinkFrames.append(shipAnimatedAtlas.textureNamed(shipTextureName))
    }

    shipAnimationFrames = blinkFrames
Run Code Online (Sandbox Code Playgroud)

任何帮助都是极好的!

Luc*_*tti 5

纹理图集

首先,你需要创建一个纹理图集Assets.xcassets.你会在这里放置与你角色的帧相关的图像.

在此输入图像描述

子类化SKSpriteNode

这是使用beginAnimation方法创建自己的精灵的方法

class Croc: SKSpriteNode {

    init() {
        let texture = SKTexture(imageNamed: "croc_walk01")
        super.init(texture: texture, color: .clearColor(), size: texture.size())
    }


    func beginAnimation() {
        let textureAtlas = SKTextureAtlas(named: "croc")
        let frames = ["croc_walk01", "croc_walk02", "croc_walk03", "croc_walk04"].map { textureAtlas.textureNamed($0) }
        let animate = SKAction.animateWithTextures(frames, timePerFrame: 0.1)
        let forever = SKAction.repeatActionForever(animate)
        self.runAction(forever)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,beginAnimation方法使用我之前创建的纹理图集的相同名称创建纹理图集Assets.xcassets.

然后创建一个纹理数组(frames)并用作参数来创建animate动作.

开始动画

现在你需要创建你的精灵并beginAnimation只调用一次.您不必在任何更新方法中调用beginAnimations,否则您将在每个新帧中创建一个新动画.这是错的.beginAnimation必须只调用一次.

这是一个例子

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        let croc = Croc()
        croc.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
        addChild(croc)

        croc.beginAnimation()
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述