我想要简单的动画从阿特拉斯纹理在顺序win1,win2,win3。我的代码:
var Image = SKSpriteNode()
var ImageAtlas = SKTextureAtlas()
var ImageArray = [SKTexture]()
override func didMove(to view: SKView) {
ImageAtlas = SKTextureAtlas(named: "Images")
for i in 1...ImageAtlas.textureNames.count{
let textureName = "win\(i).png"
let texture = ImageAtlas.textureNamed(textureName)
ImageArray.append(texture)
}
let firstFrame = ImageArray[0]
Image = SKSpriteNode(texture: firstFrame)
Image.setScale(0.7)
Image.position = CGPoint(x: 0, y: self.frame.width / -1.5)
Image.zPosition = 2
self.addChild(Image)
...
Image.run(SKAction.repeatForever(SKAction.animate(with: ImageArray, timePerFrame : 0.01)))
...
当我播放动画时,纹理不在对齐win1、win2、win3中,而是在例如win3、win1、win2中。怎么了?谢谢!
最佳答案
SKTextureAtlas
textureNames
不保证数组的顺序。如果你想按一定的顺序来分类,你应该自己分类。
代码中还有一些样式问题-请注意,变量名应该使用小写字母case,否则其他人(以及SO的语法高亮器之类的工具)很难将它们与类型区分开来。这里有一个改装来修复一些东西:
// don't allocate dummy values, just leave these nil until loaded
var imageNode: SKSpriteNode!
var atlas: SKTextureAtlas!
var textures: [SKTexture]!
override func didMove(to view: SKView) {
atlas = SKTextureAtlas(named: "Images")
// sort array, convert from names to textures with map
textures = atlas.textureNames.sorted().map { atlas.textureNamed($0) }
guard let firstFrame = textures.first
else { fatalError("missing textures") }
imageNode = SKSpriteNode(texture: firstFrame)
imageNode.setScale(0.7)
imageNode.position = CGPoint(x: 0, y: self.frame.width / -1.5)
imageNode.zPosition = 2
self.addChild(imageNode)
}
...
// use implicit member lookup for terser syntax
imageNode.run(.repeatForever(.animate(with: textures, timePerFrame: 0.01)))
这里唯一要注意的是Swift标准库的
sorted()
是对字符串的简单排序:如果有超过10个名为win1, win2, ..., win10, win11
的纹理,它会将它们排序为win1, win10, win11, win2, ...
。您可以通过使用NSArray
中的某些桥接排序方法(这些方法使用区域设置感知比较)来更正此问题。