一段时间后删除SKLabel

时间:2016-06-10 14:19:55

标签: xcode swift sklabelnode

所以我只是在xcode中乱七八糟地遇到了一个问题。我创建了一个系统,每当用户触摸屏幕上的任何位置时,它就会创建一个用户触摸的随机颜色的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 */
}

1 个答案:

答案 0 :(得分:1)

使用sequence SKAction代替当前的waitForDuration操作,其中包含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)
}