首页 > 解决方案 > 如何修复随机数量的 for 循环?

问题描述

我正在使用 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)

}

预期的结果是,当调用函数时,动画应该运行一次并删除自己。相反,它运行一次最多 10 次左右。

标签: arraysswiftanimationsprite-kitinfinite-loop

解决方案


感谢@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)

}

推荐阅读