我已经脱离 swift 循环有一段时间了,但我遇到了一个数组问题。 我感觉我的做法完全错误,我这样做是为了清理重复的代码。我在一个循环中有一个循环,似乎正在工作,但有一个例外:当我输出时,我从第一个循环中获得了所有 4 次迭代,这在某种程度上很好,因为我想要所有的迭代,但我想将它们放在一个变量中之前第二次迭代开始...我希望这是有道理的,我可能会以我正在做的方式走上几英里,任何帮助将不胜感激。
struct Action {
static var arraySprites :[SKTexture], [SKTexture]()
static var Idle = [SKTexture]()
}
var actions = ["idle", "walk", "run", "jump"]
var sprites = ["Idle", "Walk", "Run", "Jump"]
for (e1, e2) in zip(actions, sprites) {
let e1Atlas = SKTextureAtlas(named: "\(e2)")
var e1Frames: [SKTexture] = []
let e1Images = (e1Atlas.textureNames.count-1)
for i in 0...(e1Images) {
let sprite = String(format: "%03d", i);
let e1Texture = "\(e1)\(sprite)"
e1Frames.append(e1Atlas.textureNamed(e1Texture))
}
/*gives me all four iterations of the for loop I want to somehow get iteration 1,2,3,4 and assign them to glabal variables*/
print(e1Frames[0])
}
更新:我找到了这个解决方案,虽然有点粗糙,但我仍在掌握这个...我(非常)愿意接受更好的方法,它可以为不同的操作吐出 4 个精灵数组...
let sprites = ["idle", "walk", "run", "jump"]
for (index, action) in sprites.enumerated() {
let atlas = SKTextureAtlas(named: "\(action)")
var frames: [SKTexture] = []
let images = (atlas.textureNames.count-1)
for i in 0...(images) {
let sprite = String(format: "%03d", i);
let texture = "\(action)\(sprite)"
frames.append(atlas.textureNamed(texture))
}
switch (index) {
case 0:
playerIdle = frames
case 1:
playerWalk = frames
case 2:
playerRun = frames
case 3:
playerJump = frames
default:
print ("Default")
}
}
我认为你最终想要得到的是每个不同动作状态的纹理数组,idle,walk,run,jump。
我会使用字符串原始值为这些状态创建一个
enum
。
然后,您可以创建一个由枚举值作为键控的纹理数组字典。
enum Action:String, CaseIterable {
case idle="idle"
case walk="walk"
case run="run"
case jump="jump"
}
var actionSprites = [Action:[SKTexture]]()
for action in Action.allCases {
let e1Atlas = SKTextureAtlas(named: action.rawValue)
var textures = [SKTexture]()
for i in 0..<e1Atlas.textureNames.count {
let imageNumber = String(format: "%03d", i);
let textureName = "\(action.rawValue)\(imageNumber)"
textures.append(e1Atlas.textureNamed(textureName))
}
actionSprites[action] = textures
}
一旦有了这个,您就可以使用
actionSprites[.run]
找到特定动作(例如跑步)的纹理