如何修复随机的for循环?

时间:2019-09-02 22:20:58

标签: arrays swift animation sprite-kit infinite-loop

我正在使用SpriteKit创建一个游戏(太空射击游戏)。当前在游戏中添加动画。当爆炸产生时,动画将循环播放X次(实际上是随机的)。有时它将循环3次,有时最多10次。屏幕最终充满了毫无意义的爆炸动画。

我曾经有一个简单的淡入/淡出动画,效果很好,但最终升级为更平滑的动画。我介绍了一个for循环,它给了我这个问题。我也尝试过使用while循环,但无济于事。我已经尝试过不按顺序使用动画,但这也无法解决任何问题。

func spawnExplosion(spawnPosition: CGPoint) {

    var explosion = SKSpriteNode()

    textureAtlas = SKTextureAtlas(named: "explosion")

    for i in 1...textureAtlas.textureNames.count {

        let name = "explosion\(i).png"
        textureArray.append(SKTexture(imageNamed: name))
        print(i)
    }

    explosion = SKSpriteNode(imageNamed: "explosion1.png" )
    explosion.setScale(0.6)
    explosion.position = spawnPosition
    explosion.zPosition = 3
    self.addChild(explosion)
    print(textureAtlas.textureNames.count)

    //explosion animation-action
    let explosionAnimation = SKAction.repeat(SKAction.animate(with: textureArray, timePerFrame: 0.05), count: 1)
    let delete = SKAction.removeFromParent()
    let explosionSequence = SKAction.sequence([explosionSound, explosionAnimation, delete])
    explosion.run(explosionSequence)

}

预期结果是,在调用函数时,动画应通过ONCE运行并删除自身。相反,它最多可以运行10次左右。

1 个答案:

答案 0 :(得分:1)

由于@ Knight0fDragon,我能够通过将纹理数组放置在函数内部来解决此问题。现在每个爆炸都有它自己的实例。

    func spawnExplosion(spawnPosition: CGPoint) {
    var explosion = SKSpriteNode()
    var textureAtlas = SKTextureAtlas()
    var textureArray = [SKTexture]()

    textureAtlas = SKTextureAtlas(named: "explosion")

    for i in 1...textureAtlas.textureNames.count {

        let name = "explosion\(i).png"
        textureArray.append(SKTexture(imageNamed: name))
    }

    explosion = SKSpriteNode(imageNamed: "explosion1.png" )
    explosion.setScale(0.6)
    explosion.position = spawnPosition
    explosion.zPosition = 3
    self.addChild(explosion)

    //explosion animation-action
    let explosionAnimation = SKAction.repeat(SKAction.animate(with: textureArray, timePerFrame: 0.05), count: 1)
    let delete = SKAction.removeFromParent()
    let explosionSequence = SKAction.sequence([explosionSound, explosionAnimation, delete])
    explosion.run(explosionSequence)

}