无法对齐数组中的图像(图集) - SpriteKit

时间:2017-02-27 19:51:12

标签: ios arrays swift xcode for-loop

我希望在命令win1,win2,win3中使用atlas纹理的简单动画。我的代码:

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。怎么了。谢谢!

3 个答案:

答案 0 :(得分:1)

SKTextureAtlastextureNames对数组的顺序没有任何承诺。如果您按照特定顺序要求它们,则应自行分类。

您的代码中还存在一些样式问题 - 请注意,变量名称应该位于lowerCamelCase中,或者其他人(以及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()对于字符串是一种天真的排序:如果你有超过十个纹理,其名称为win1, win2, ..., win10, win11,它会将它们排序为win1, win10, win11, win2, ...。您可以使用NSArray中使用区域设置感知比较的一些桥接排序方法来纠正此问题。

答案 1 :(得分:1)

在创建动画时,以下内容通常适用于我。

class GameScene: SKScene {

   var TextureAtlas = SKTextureAtlas()
   var playerArray = [SKTexture]()

override func didMove(to view: SKView) {

                   //just replace "playerWon" with the name of your atlas folder
   TextureAtlas = SKTextureAtlas(named: "playerWon") 
   for i in 1...TextureAtlas.textureNames.count {
       let Name = "win\(i).png" //replace "win" with whatever name your .png files have
       playerArray.append(SKTexture(imageNamed: Name))
     }

   let playerNode = SKSpriteNode(imageNamed: TextureAtlas.textureNames[0])


   }



 }

答案 2 :(得分:-1)

最后!两个代码都有效!谢谢!对我来说,它没有用,因为在地图集中缓存了旧的信息。我必须使用清洁功能。 (产品 - >清洁)。