【问题标题】:Removing a sprite in an if statement with SpriteKit使用 SpriteKit 删除 if 语句中的精灵
【发布时间】:2015-09-12 17:49:01
【问题描述】:

我想制作一款游戏,每次用户触摸时,它都会在两种“状态”之一之间切换。为了跟踪触摸,我创建了一个名为 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

}

当我运行代码时,根据条件添加了新纹理,但旧纹理仍然存在。它们被添加为场景中的新精灵节点。我不想要这个。我期待它根据我的布尔变量在activeState spritenode 的纹理(state0state1)之间简单地切换。如何让我的代码在每次用户点击时在纹理之间切换,而不是将新的 spritenode 堆叠在一起?

【问题讨论】:

  • 尝试做一些println() 日志并告诉我们发生了什么。就像在您的 if 语句中一样,以确保它们实际上被调用了。另外,我不会使用整数作为条件句。相反,我会使用布尔值。在我看来,使用truefalse 要容易得多。
  • 我根据你的建议(布尔值)编辑了我的代码,它仍然有类似的问题。我也尝试过让单个精灵节点在两个纹理之间切换,但这似乎不起作用。 println() 测试有效,所以我知道我的 if 语句实际上被调用了。我发布了我的新代码以帮助您了解发生了什么。
  • 您不了解基本错误。您创建本地对象并将其添加到场景中。下次您创建新的本地对象并使用新的本地对象。在您的代码中,您无权访问上一步创建的旧对象。检查我在下面留下的答案,并尝试准确了解您做错了什么

标签: ios swift macos sprite-kit


【解决方案1】:

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

  1. touchesBegan 函数之外创建纹理和SKSpriteNode 对象
  2. 如果您的场景中没有 init,请在 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
        }
    }
...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    相关资源
    最近更新 更多