我正在用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)
}
}
}
最佳答案
尝试为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)
}
如果只希望在触碰节点时使用TouchStarted方法,请执行以下操作:
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)
}
}
}
如果希望该节点与任何地方接触,请尝试将该节点放在局部变量中
希望这有帮助
关于ios - 如何召回SKLabelNode,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57080335/