在 SwiftUI 视图中显示 SpriteKit 分数

Show SpriteKit score in SwiftUI View

我正在尝试制作一个 ZStack 来覆盖我的 SpriteKit 场景中的乐谱。我现在得到了以下代码,它可以在实际场景中显示代码,但我想在视图中显示它

import SwiftUI
import SpriteKit

var gameScore = 0

class GameScene: SKScene, SKPhysicsContactDelegate {

let removeLabel = SKAction.sequence([SKAction.fadeIn(withDuration: 0.3), SKAction.wait(forDuration: 0.8), SKAction.fadeOut(withDuration: 0.3)])

override func sceneDidLoad() {
    super.sceneDidLoad()
}

函数如下:

// MARK: - Add Score
func addScore(){
    if gameScore < 250 {
        gameScore += 1
        scoreLabel.text = String(format: "%06d", gameScore)
        let possibleScores: Set = [10, 20, 30, 40, 50, 65, 80, 95, 110, 125, 150, 175, 200, 250]
        
        if possibleScores.contains(gameScore) {
            startNewLevel()
        }
    } else {
        gameScore += 2
        scoreLabel.text = String(format: "%06d", gameScore)
        let possibleScores: Set = [10, 20, 30, 40, 50, 65, 80, 95, 110, 125, 150, 175, 200, 250]
        
        if possibleScores.contains(gameScore) {
            startNewLevel()
        }
    }
}

我的视图代码如下所示:

import SwiftUI
import SpriteKit

struct PageTwo: View {

@State var gameScore = 0

var body: some View {
    ZStack {
        GameView()
        ZStack {
            Text("Score: \(gameScore)")
                .foregroundColor(.white)
      }
    }
  }
}

它显示了分数,但没有计算它,所以也许有人可以告诉我我哪里出错了?这个 SpriteKit + SwiftUI 对我来说是新手,但还是不太了解。

您需要为此使用 ObservableObject 和发布者,我查看了您的代码,缺少一些代码源,但它是您的示例:

class GameScene: SKScene, SKPhysicsContactDelegate, ObservableObject {  // <<: Here 1
    
    @Published var gameScore = 0 // <<: Here 2
    
    let removeLabel = SKAction.sequence([SKAction.fadeIn(withDuration: 0.3), SKAction.wait(forDuration: 0.8), SKAction.fadeOut(withDuration: 0.3)])
    
    override func sceneDidLoad() {
        super.sceneDidLoad()
    }
    
    func addScore(){
        if gameScore < 250 {
            gameScore += 1
            
        } else {
            gameScore += 2
            
        }
    }
    
}



struct PageTwo: View {
    
    @StateObject var gameScene: GameScene = GameScene() // <<: Here 3
    
    var body: some View {
        
        Text("Score: \(gameScene.gameScore)") // <<: Here 4
            .onTapGesture {
                gameScene.addScore()  // <<: Here 5
            }
        
    }
    
}