Swift 尝试用字符串数组交叉检查 SKActions 数组

Swift trying to cross check array of SKActions with array of strings

您好,我正在尝试使用字符串从 SKAction 数组中选择一个 SKAction

我有一个数组,其中包含我的游戏中所有可能的 SKAction。然后我需要提取与选定节点的可能操作名称(字符串)相匹配的特定操作。

所以,例如,我可能

allActions = [runCentre, runLeft, runRight] 

那些是 SKActions,

possibleActions = [runCentre, runRight] 

这是从与给定节点类型相关的 属性 列表中访问的字符串。

如何在 allActions 数组中查询 possibleActions 中的值?我知道遍历两个数组的机制,但不知道我实际尝试访问的内容。我能以某种方式给 SKActions 一个字符串 属性 吗?我试过了

runStraight.setValue("runStraight", forKey: "name")  

但这会引发 NSUnknownKeyException。有更好的方法吗?

非常感谢任何帮助!

将所有操作的列表保存在类型为 [String:SKAction] 的字典中。

let allActions = [
    "runCenter": runCenter,
    "runLeft": runLeft,
    // etc
]

如果您在 String 数组中有一个节点的可能操作,您可以使用 (flat)Map。

let possibleActions = ["runCenter", "idle"]

let possibleSKActions = possibleActions.flatMap { allActions[[=11=]] }

// or if we are sure the action names will always have a value
let possibleSKActions = possibleActions.map { allActions[[=11=]]! }

我真的不是很明白你想达到什么目的。 不幸的是,SKAction 没有 tagname 属性 作为标识。 您可以创建字典以将字符串键关联到 SKAction

假设您有这些操作:

let runCentre = SKAction.move(to: CGPoint(x:100.0,y:100.0), duration: 1.0)
let runLeft = SKAction.move(to: CGPoint(x:0.0,y:100.0), duration: 1.0)
let runRight = SKAction.move(to: CGPoint(x:200.0,y:100.0), duration: 1.0)
let runTop = SKAction.move(to: CGPoint(x:100.0,y:200.0), duration: 1.0)
let runBottom = SKAction.move(to: CGPoint(x:100.0,y:0.0), duration: 1.0)
// create a dictionary (key:string, value:SKAction)
let allActions = ["runCentre":runCentre,"runLeft":runLeft,"runRight": runRight,"runTop":runTop,"runBottom":runBottom]

您可以使用以下方法构建字典:

let allActions = ["runCentre":runCentre,"runLeft":runLeft,"runRight": runRight,"runTop":runTop,"runBottom":runBottom]

现在假设您有一个具有以下可能操作的节点:

let runDiag = SKAction.move(to: CGPoint(x:0.0,y:200.0), duration: 1.0)
let possibleActions = ["runCentre":runCentre, "runRight": runRight, "runDiag":runDiag]

要知道 possibleActionsallActions 中可用的内容(依赖于等键),您可以这样做:

let availableActions = allActions.filter { possibleActions.keys.contains([=13=].key) }