我想制作一个游戏,每次用户触摸时,它会在两个“状态”之一之间切换。为了跟踪触摸,我创建了一个名为userTouches的变量,每次用户触摸时都会从true变为false。我想这样做,如果numberOfTouches为真,它将纹理更新为state0;如果它是假的,它会将纹理更新为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
}
当我运行代码时,新的纹理会根据条件添加,但旧的纹理仍然存在。它们被添加为场景中的新spritenodes。我不想要这个。我希望它只是根据我的布尔变量在state0
spritenode的纹理(state1
和activeState
)之间切换。每次用户点击时,如何让我的代码在纹理之间切换,而不是将新的spritenodes堆叠在一起?
答案 0 :(得分:1)
每次创建新对象时,更改其纹理(新对象的纹理,但不是上次设置的对象纹理)并将其添加到场景中。这就是为什么添加新对象并且旧对象没有任何反应的原因。 这样做,它将解决您的问题:
touchesBegan
函数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
}
}
...
}