【问题标题】:How to properly animate SKSpriteNode subclasses如何正确地为 SKSpriteNode 子类设置动画
【发布时间】:2016-08-04 18:36:46
【问题描述】:

我设计了一个 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())

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

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

        print("animate")
    }

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

任何帮助都会很棒!

【问题讨论】:

    标签: swift animation sprite-kit


    【解决方案1】:

    纹理图集

    首先您需要在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")
        }
    }
    

    如您所见,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()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-12
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 2014-11-19
      相关资源
      最近更新 更多