ios - 使用 SpriteKit 删除 if 语句中的 Sprite

标签 ios swift macos sprite-kit

我想制作一款游戏,每次用户触摸时,它都会在两种“状态”之一之间切换。为了跟踪触摸,我创建了一个名为 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 的纹理(state0state1)之间切换。我怎样才能让我的代码在每次用户点击时在纹理之间切换,而不是将新的 Sprite 节点堆叠在一起?

最佳答案

每次创建一个新对象时,改变它的纹理(新对象的纹理,而不是上次设置的对象的纹理)并将其添加到场景中。这就是添加新对象而旧对象没有任何反应的原因。 这样做,它会解决你的问题:

  1. touchesBegan 函数之外创建纹理和 SKSpriteNode 对象
  2. 如果您的场景中没有初始化,例如在 didMoveToView 函数中创建 SKSpriteNode 对象并将其添加到场景中
  3. 然后在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/

相关文章:

ios - collectionView 在标题中隐藏我的自定义 View

macos - 在 OS X Yosemite Finder 预览中显示 PNG 文件的尺寸

objective-c - 有没有办法在给定表格中选定单元格的行和列索引的情况下获取 NSCell 对象?

ios - 缩放时如何在 UIView 周围保持一致的 2px 边框?

iOS - 某些单元格不会调用 applyLayoutAttributes

ios - HKObserverQuery 后台传递在调用completionHandler 后停止工作

swift - 如何连续创建多个标签和 UIbutton?就像下面的布局

ios - MacOS 上的 SceneKit OverlaySKScene 不可见

ios - 如何从 SKView 中删除场景?

ios - 适用于iOS的AIR应用