1

Xcode 13 测试版 2,iOS 15 测试版 2。

以下代码产生一个灰屏:
SKScene GameScene.didMove(to:)永远不会被调用)

import SwiftUI
import SpriteKit

// A simple game scene with falling boxes
class GameScene: SKScene {
    override func didMove(to view: SKView) {
        physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let location = touch.location(in: self)
        let box = SKSpriteNode(color: SKColor.red, size: CGSize(width: 50, height: 50))
        box.position = location
        box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 50, height: 50))
        addChild(box)
    }
}

// A sample SwiftUI creating a GameScene and sizing it at 300x400 points
struct ContentView: View {
    var scene: SKScene {
        let scene = GameScene()
        scene.size = CGSize(width: 300, height: 400)
        scene.scaleMode = .fill
        return scene
    }

    var body: some View {
        SpriteView(scene: scene)
            .frame(width: 300, height: 400)
            .ignoresSafeArea()
    }
}

我不知道如何修复/解决此问题。
有什么想法吗?

(适用于以前的 Xcode / Swift 版本)

4

2 回答 2

1

该问题已在 Xcode 13 beta 5 / iOS 15 beta 5 中修复。

于 2021-08-11T06:58:45.717 回答
0

这可能是因为场景是一个计算变量。因此,每次重绘视图或访问场景时,都会重新计算它,从而创建并初始化一个新GameScene对象。尝试更多类似的东西,其中GameModelGameScene只创建一次。(您可能可以改进它并消除必须设置两次大小):

class GameScene: SKScene { // keep the same }

class GameModel: ObservableObject {
  let scene: SKScene = {
    let scene = GameScene()
    scene.size = CGSize(width: 300, height: 400)
    scene.scaleMode = .fill
    return scene
  }()
}

struct ContentView: View {
    @StateObject var model = GameModel()
    var body: some View {
      SpriteView(scene: model.scene)
        .frame(width: 300, height: 400)
            .ignoresSafeArea()
    }
}
于 2021-07-11T23:26:37.257 回答