首页 > 解决方案 > 将节点的精灵更改为动画(spriteKit)

问题描述

我对 swift 很陌生,我用硬币精灵制作了一个精灵套件游戏。我想让它旋转,所以我总共制作了 6 个精灵。我试图通过快速更改精灵来获得连续的旋转循环。我试图用下面的代码来做到这一点。

    //This will hold all of the coin spinning sprites
    let coinTextures : NSMutableArray = []

    //There are 6 in total, so loop through and add them
    for i in 0..<6 {
        let texture : SKTexture = SKTexture(imageNamed: "Coin\(i + 1)")
        coinTextures.insert(texture, at: i)
    }

    //When printing coinTextures, they have all been added
    //Define the animation with a wait time of 0.1 seconds, also repeat forever
    let coinAnimation = SKAction.repeatForever(SKAction.animate(with: coinTextures as! [SKTexture], timePerFrame: 0.1))

    //Get the coin i want to spin and run the action!
    SKAction.run(coinAnimation, onChildWithName: "coin1")

正如我所说,我很新,所以我不确定我在这里做错了什么。

我要旋转的硬币的名称也是“coin1”,精灵是从 coin1 到 coin 6

标签: swiftsprite-kit

解决方案


你快到了。

问题是你的最后一行创建了一个动作,但没有在任何东西上运行它......

你有两个选择:

1)在你的场景中运行你的动作

// Create an action that will run on a child
let action = SKAction.run(coinAnimation, onChildWithName: "coin1")
scene?.run(action)

或者

2)直接在孩子身上运行动作

// Assuming that you have a reference to coin1
coin1.run(coinAnimation)

作为旁注,您的数组可以声明为var coinTextures: [SKTexture] = [],您可以使用append它向其中添加项目并在将纹理传递给动作时避免强制转换。

或者您可以使用更紧凑的形式来构建您的纹理数组:

let coinTextures = (1...6).map { SKTexture(imageNamed: "Coin\($0)") }

我希望这是有道理的


推荐阅读