簡體   English   中英

使用SpriteKit在if語句中刪除精靈

[英]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的紋理( state0state1 )之間切換。 我如何讓我的代碼在用戶每次點擊時在紋理之間切換,而不是在彼此之上疊加新的spritenode?

每次創建新對象時,都要更改其紋理(新對象的紋理,而不是上次設置的對象的紋理),然后將其添加到場景中。 這就是為什么要添加新對象,而舊對象什么也沒有發生的原因。 這樣做,它將解決您的問題:

  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
        }
    }
...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM