如何召回SKLabelNode

时间:2019-07-17 16:18:45

标签: ios swift addchild sklabelnode

我正在与SpriteKit进行游戏。

我正在尝试添加一个SKLabelNode(pointsLabel),如果我没有设置label.isHidden = true,我就可以使用它。但是,我希望在touchesBegan之前隐藏标签,但是似乎无法在此函数中调用LabelNode,因此标签保持隐藏状态。

我如何使其工作?

这是代码:

class GameScene: SKScene {

private var pointsLabel: SKLabelNode?

override func didMove(to view: SKView) {
    pointsLabelShow()
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    // Get label node from scene and store it for use later
    self.label = self.childNode(withName: "//pointsLabel") as? SKLabelNode
    if let label = self.label {
        label.isHidden = false
        let fade = SKAction.fadeIn(withDuration: 0.2)
        let sequence = SKAction.sequence([fade])
        label.run(sequence)

    }    
}

override func update(_ currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */

    self.label = self.childNode(withName: "//pointsLabel") as? SKLabelNode
    if let label = self.label {
        label.position.y = ballHeight + 840
    }

    func pointsLabelShow() {
        let pointsLabel = SKLabelNode(fontNamed: "orkneymedium")
        pointsLabel.isHidden = true
        pointsLabel.text = "000"
        pointsLabel.fontSize = 50
        pointsLabel.fontColor = SKColor.white
        self.addChild(pointsLabel)
    }
}

}

1 个答案:

答案 0 :(得分:0)

尝试为SKLabelNode命名,假设“ pointsLabel”

func pointsLabelShow() {
        let pointsLabel = SKLabelNode(fontNamed: "orkneymedium")
        pointsLabel.isHidden = true
        pointsLabel.text = "000"
        pointsLabel.fontSize = 50
        pointsLabel.name = "pointsLabel"
        pointsLabel.fontColor = SKColor.white
        self.addChild(pointsLabel)

    }

如果仅在触摸时才需要该节点,请在TouchsBegan方法中执行以下操作:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first!
    let positionInScene = touch.location(in: self)
    let touchedNode = self.atPoint(positionInScene)

    if let name = touchedNode.name
    {
        if name == "pointsLabel"
        {
            touchedNode.isHidden = false
            let fade = SKAction.fadeIn(withDuration: 0.2)
            let sequence = SKAction.sequence([fade])
            touchedNode.run(sequence)
        }
    }
}

如果您希望节点在任何地方都可以接触,请尝试将节点放入局部变量

希望这会有所帮助