2016-06-10 62 views
1

所以我只是在xcode messin周圍,我遇到了一個問題。我創建了一個系統,每當用戶觸摸屏幕上的任何位置時,都會在用戶觸摸的位置創建一個隨機顏色的SKLabel。我怎麼能讓所創建的SKLabel消失,或者說在5秒之後從場景中移除?由於一段時間後刪除SKLabel

import SpriteKit 

class GameScene: SKScene { 

func createNateLabel(touchLocation: CGPoint){ 

    let nate = SKLabelNode(fontNamed: "Chalduster") 

    let randomNumber = Int(arc4random_uniform(UInt32(8))) 

    if randomNumber == 0 { 

     nate.fontColor = UIColor.cyanColor() 

    } 

    if randomNumber == 1{ 

     nate.fontColor = UIColor.redColor() 

    } 
    if randomNumber == 2{ 

     nate.fontColor = UIColor.blueColor() 

    } 
    if randomNumber == 3{ 

     nate.fontColor = UIColor.purpleColor() 

    } 
    if randomNumber == 4{ 

     nate.fontColor = UIColor.yellowColor() 

    } 
    if randomNumber == 5{ 

     nate.fontColor = UIColor.greenColor() 

    } 
    if randomNumber == 6{ 

     nate.fontColor = UIColor.orangeColor() 

    } 
    if randomNumber == 7{ 

     nate.fontColor = UIColor.darkGrayColor() 

    } 
    if randomNumber == 8{ 

     nate.fontColor = UIColor.yellowColor() 

    } 

    if nate == true{ 

     let wait = SKAction.waitForDuration(3) 

     nate.runAction(wait) 


     nate.removeAllChildren() 
    } 


    nate.text = "Nate" 
    nate.fontSize = 35 
    nate.position = touchLocation 
    addChild(nate) 

} 

override func didMoveToView(view: SKView) { 

} 

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 

    let touch = touches.first! as UITouch 
    let touchLocation = touch.locationInNode(self) 

     createNateLabel(touchLocation) 

    } 
} 

func update(currentTime: CFTimeInterval) { 
    /* Called before each frame is rendered */ 
} 
+0

創建一個計時器來清除它們 –

回答

1

而非目前waitForDuration行動,使用sequence SKAction包括waitForDuration動作後跟一個removeFromParent作用。

請注意,您當前的removeAllChildren調用不會執行任何操作,因爲您的標籤節點沒有要刪除的子節點。

(編輯:糾正組序列)


(由@vacawama編輯):我不覺得需要一個第二個答案,所以我加入這@ AliBeadle的優良的答案。這是一個功能createNateLabel,它使用SKAction.sequence 5秒後刪除標籤。我也把顏色放在一個陣列中,以便選擇一個隨機的清潔器:

func createNateLabel(touchLocation: CGPoint){ 

    let nate = SKLabelNode(fontNamed: "Chalkduster") 

    let colors: [UIColor] = [.cyanColor(), .redColor(), .blueColor(), .purpleColor(), .yellowColor(), .greenColor(), .orangeColor(), .darkGrayColor(), .yellowColor()] 

    nate.text = "Nate" 
    nate.fontSize = 35 
    nate.fontColor = colors[Int(arc4random_uniform(UInt32(colors.count)))] 
    nate.position = touchLocation 
    addChild(nate) 

    let wait = SKAction.waitForDuration(5) 
    let remove = SKAction.removeFromParent() 
    let sequence = SKAction.sequence([wait, remove]) 

    nate.runAction(sequence) 
} 
相關問題