arrays - 如何修复随机数量的 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 次左右。
解决方案
感谢@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)
}
推荐阅读
- php - Text is not changing when is being read
- java - 无法使用来自 IPSwitch 客户端的 Jsch 和私钥建立与 unix 服务器的连接
- asp.net - 为什么 VS2019 / VB.Net /EF 6 要求我的进口量加倍?
- shell - 是否存在用于常见提示的 COM Shell 接口?
- python-3.x - NameError: name 'XYZ' is not defined [WARN:1] terminating async callback
- sparql - 如何读取对象属性的特定范围值
- css - 网站滚动问题。使用 ReactJS
- javascript - 如何在 iframe 或 localhost 中显示用户提交网站的预览?
- android - 在不依赖单例的情况下,在 MVVM 中的视图之间共享显示状态
- python - 在 Python 中打印键、值对时如何按字段对齐打印输出