[英]Removing a sprite in an if statement with SpriteKit
我想制作一个游戏,每次用户触摸时,它都会在两个“状态”之一之间切换。 为了跟踪触摸,我创建了一个名为userTouches的变量,该变量在每次用户触摸时从true变为false。 我想这样做,如果numberOfTouches为true,它将纹理更新为state0; 如果为假,则将纹理更新为state1。 每次触摸几乎只在状态0和状态1之间切换。
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
}
当我运行代码时,会根据条件添加新的纹理,但是旧的纹理仍然存在。 它们被添加为场景中的新spritenode。 我不想这样。 我期望它可以根据我的布尔变量简单地在activeState
spritenode的纹理( state0
和state1
)之间切换。 我如何让我的代码在用户每次点击时在纹理之间切换,而不是在彼此之上叠加新的spritenode?
每次创建新对象时,都要更改其纹理(新对象的纹理,而不是上次设置的对象的纹理),然后将其添加到场景中。 这就是为什么要添加新对象,而旧对象什么也没有发生的原因。 这样做,它将解决您的问题:
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
}
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.