我想制作一款游戏,每次用户触摸时,它都会在两种“状态”之一之间切换。为了跟踪触摸,我创建了一个名为 userTouches 的变量,每次用户触摸时该变量都会从 true 变为 false。我想这样做,如果 numberOfTouches 为真,它会将纹理更新为 state0;如果为 false,则将纹理更新为 state1。几乎只是在每次触摸时在 state0 和 state1 之间切换。
var userTouches: Bool = true
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch in (touches as! Set<UITouch>) {
userTouches = !userTouches
}
let centered = CGPoint(x: size.width/2, y: size.height/2)
let state0 = SKTexture(imageNamed:"state0")
let state1 = SKTexture(imageNamed:"state1")
var activeState: SKSpriteNode = SKSpriteNode(texture: state0)
//Add new state0 if it's odd, remove old state0 if it's not.
if userTouches == true {
activeState.texture = state0
println("IT'S TRUE")
} else {
activeState.texture = state1
println("IT'S FALSE")
}
self.addChild(activeState)
activeState.name = "state0"
activeState.xScale = 0.65
activeState.yScale = 0.65
activeState.position = centered
}
当我运行代码时,根据条件添加了新纹理,但旧纹理仍然存在。它们被添加为场景中的新 Sprite 节点。我不想要这个。我希望它能够根据我的 bool 变量在 activeState
spritenode 的纹理(state0
和 state1
)之间切换。我怎样才能让我的代码在每次用户点击时在纹理之间切换,而不是将新的 Sprite 节点堆叠在一起?
最佳答案
每次创建一个新对象时,改变它的纹理(新对象的纹理,而不是上次设置的对象的纹理)并将其添加到场景中。这就是添加新对象而旧对象没有任何反应的原因。 这样做,它会解决你的问题:
- 在
touchesBegan
函数之外创建纹理和 SKSpriteNode 对象 - 如果您的场景中没有初始化,例如在
didMoveToView
函数中创建 SKSpriteNode 对象并将其添加到场景中 - 然后在
touchesBegan
函数中只设置贴图到SKSpriteNode对象
它看起来像这样:
class GameScene: SKScene {
...
let state0 = SKTexture(imageNamed:"state0")
let state1 = SKTexture(imageNamed:"state1")
var activeState: SKSpriteNode?
...
override func didMoveToView(view: SKView) {
let centered = CGPoint(x: size.width/2, y: size.height/2)
activeState = SKSpriteNode(texture: state0)
self.addChild(activeState!)
activeState!.name = "state0"
activeState!.xScale = 0.65
activeState!.yScale = 0.65
activeState!.position = centered
}
...
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if userTouches {
activeState!.texture = state0
} else {
activeState!.texture = state1
}
}
...
}
关于ios - 使用 SpriteKit 删除 if 语句中的 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32541891/