将节点的精灵更改为动画(spriteKit)

时间:2018-05-25 08:26:10

标签: swift sprite-kit

我是一个非常新的快速,我已经用硬币精灵做了一个精灵套件游戏。我想让它旋转,所以我总共制作了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")

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

我想要旋转的硬币的名称是&#34; coin1&#34;而精灵从coin1到coin 6

1 个答案:

答案 0 :(得分:2)

你快到了。

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

你有两种选择:

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)") }

我希望这是有道理的