gpt4 book ai didi

swift - 是否可以更新 SKLabelNode?

转载 作者:行者123 更新时间:2023-11-30 13:02:10 25 4
gpt4 key购买 nike

我正在尝试更新 coinLabel,以便当点击“life”节点时,它将更新 SKLabelNode 并在从总数中减去硬币后显示正确的硬币。我是编码新手,所以如果还有其他问题,请回复!谢谢!

import Foundation
import SpriteKit

class ShopScene: SKScene {

override func didMove(to view: SKView) {


let background = SKSpriteNode(imageNamed: "background")
background.size = self.size
background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
background.zPosition = 0
self.addChild(background)

let mainMenu = SKLabelNode(fontNamed: "The Bold Font")
mainMenu.text = "Main Menu"
mainMenu.fontSize = 100
mainMenu.fontColor = SKColor.darkGray
mainMenu.position = CGPoint(x: self.size.width*0.5, y: self.size.height*0.3)
mainMenu.zPosition = 1
mainMenu.name = "Main Menu"
self.addChild(mainMenu)

let Life = SKLabelNode(fontNamed: "The Bold Font")
Life.text = "Click here to buy 1 life!"
Life.fontSize = 130
Life.fontColor = SKColor.darkGray
Life.position = CGPoint(x: self.size.width*0.5, y: self.size.height*0.6)
Life.zPosition = 1
Life.name = "Life"
self.addChild(Life)

let coinLabel = SKLabelNode(fontNamed: "The Bold Font")
coinLabel.text = "Coins: \(coinNumber)"
coinLabel.fontSize = 100
coinLabel.fontColor = SKColor.black
coinLabel.zPosition = 1
coinLabel.position = CGPoint(x: self.size.width/2, y: self.size.height*0.1)
self.addChild(coinLabel)



}


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


for touch: AnyObject in touches {

let pointOfTouch = touch.location(in: self)
let nodeITapped = atPoint(pointOfTouch)

if nodeITapped.name == "Main Menu" {


let sceneToMoveTo = MainMenuScene(size: self.size)
sceneToMoveTo.scaleMode = self.scaleMode
let myTrasition = SKTransition.fade(withDuration: 0.5)
self.view!.presentScene(sceneToMoveTo, transition: myTrasition)
}

if nodeITapped.name == "Life" {
if coinNumber > 10 {
lifeNumber += 1
coinNumber -= 10
defaults.set(coinNumber, forKey: "coinNumberSaved")
defaults.set(lifeNumber, forKey: "lifeNumberSaved")


return

}


}
}


}


}

最佳答案

只需再次更新点击识别器中的文本即可进行更改

coinLabel.text = "Coins: \(coinNumber)"

您需要确保在 init 之外有一个 coinLabel 的引用,以便您可以在其之外操作它。在 ShopScene 的顶部,您可以执行以下操作...

class ShopScene: SKScene {
var coinLabel = SKLabelNode()
//your code
}

然后当你在 didMove(to view:) 函数中进入 init 时,请执行...

 coinLabel = SKLabelNode(fontNamed: "The Bold Font")

这样您就可以在整个代码中引用它。尽管将来您会考虑创建 SKNode 的子类来处理所有 UI 元素,这样您就不必初始化 GameScene 中的所有内容。

关于swift - 是否可以更新 SKLabelNode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39801138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com