我有3组精灵(EnemyGroups),这些组按特定顺序排列(每组精灵延迟一秒)。请参阅代码:
EnemyGroup:
struct EnemyGroup {
var enemies : [Enemy]
var isVisible : Bool
var isStatic : Bool
func setup () {
if isStatic {
for enemy in enemies {
enemy.sprite.alpha = 1.0
enemy.sprite.isUserInteractionEnabled = false
}
isVisible = true
}
}
mutating func switchEnemiesON () {
if !isStatic {
for enemy in enemies {
enemy.sprite.alpha = 1.0
enemy.sprite.physicsBody?.categoryBitMask = enemyCategory
enemy.sprite.physicsBody?.collisionBitMask = bombCategory
}
isVisible = true
}
}
mutating func switchEnemiesOFF () {
if !isStatic {
for enemy in enemies {
enemy.sprite.alpha = 0.0
enemy.sprite.physicsBody?.collisionBitMask = 0
enemy.sprite.physicsBody?.categoryBitMask = 0
}
isVisible = false
}
}
在GameScene中:
func groupActionSequence (enemyGroup: EnemyGroup) {
for enemy in enemyGroup.enemies {
var enemyGroupWithAction = enemyGroup
let groupSequence = SKAction.sequence([
SKAction.run({ enemyGroupWithAction.switchEnemiesON() }),
SKAction.wait(forDuration: showTime),
SKAction.run({ enemyGroupWithAction.switchEnemiesOFF() }),
SKAction.wait(forDuration: hideTime)
])
let repeatGroupAction = SKAction.repeatForever(groupSequence)
enemy.sprite.run(repeatGroupAction)
}
}
func groupActionSequenceWithDelay (delayTime: TimeInterval, enemyGroup: EnemyGroup, groupKey: String) {
for enemy in enemyGroup.enemies {
var group = enemyGroup
let groupSequence = SKAction.sequence([
SKAction.run({ group.setup() }),
SKAction.wait(forDuration: delayTime),
SKAction.run({ self.groupActionSequence(enemyGroup: enemyGroup) })
])
enemy.sprite.run(groupSequence, withKey: groupKey)
}
}
为敌方群体设置行动:
groupActionSequenceWithDelay(delayTime: 0, enemyGroup: enemyGroup1, groupKey: "group1")
groupActionSequenceWithDelay(delayTime: 1, enemyGroup: enemyGroup2, groupKey: "group2")
groupActionSequenceWithDelay(delayTime: 2, enemyGroup: enemyGroup3, groupKey: "group3")
我将enemyGroup1
和enemyGroup2
设置为isStatic = false
,将enemyGroup3
设置为isStatic = true
。
我将enemyGroup1
和enemyGroup2
isStatic
更改为true
仍然在enemyGroup1
和enemyGroup2 as if
上运行的操作isStatic = false . How can I get
switchEnemiesOFF()and
switchEnemiesON()to recognize changes in the value of
isStatic`?
此外,我不想停止操作,因为我希望保持每个组的相同序列在其运行操作中有一秒的差异,这就是为什么我用if语句保护某些函数的原因
答案 0 :(得分:1)
让EnemyGroup成为一个类而不是一个Struct。
因为它是一个Struct,所以在运行块闭包中捕获的enemyGroupWithAction变量是您在参数中收到的变量(它也是作为参数传递给函数的副本的副本)。这些副本中的每一个都有自己独立的值(Struct是值类型)并且分开存在。如果enemyGroup是一个对象(类),则只捕获引用(类是引用类型),对属性的任何修改都会影响原始对象实例。