也许我没有正确理解 UIViewRepresentable 但我认为这会起作用。
我正在尝试使用两个 UIViewRepresentable 类在 SwiftUI 中显示我的 scnkit 场景。我还为类使用两种协调器方法,各一种。协调器可以访问当前场景的渲染和物理世界方法。
玩家在第一个场景中生成,当与敌人接触时,它会转换到第二个场景。 这就是问题开始的地方,它不允许第二个协调器处理第二个类的物理世界和渲染方法。
我相信这是因为即使场景发生变化,我仍然使用 swiftui 中的第一个类而不是第二个类。或者换句话说,我正在改变场景,但没有改变正在使用的类。
问题:如何从第一类过渡到第二类和/或从第一个场景过渡到另一个场景,并且仍然让每个场景的协调员处于活动状态。
这是第一堂课。
struct FirstClass : UIViewRepresentable {
var view = SCNView()
var scene = SCNScene(named: "First.scn")!
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> SCNView {
scene.physicsWorld.contactDelegate = context.coordinator
view.delegate = context.coordinator
return view
}
...
/// Transitions into the second scene.
func changeScenes() {
controlManager.jumped = false
let transition = SKTransition.fade(with: .black, duration: 0.5)
let secondClass = SecondClass()
view.present(secondClass.scene, with: transition, incomingPointOfView: nil)
}
}
这是第二堂课
struct SecondClass : UIViewRepresentable {
var view = SCNView()
var scene = SCNScene(named: "Second.scn")!
func makeCoordinator() -> SecondCoordinator {
SecondCoordinator(self)
}
func makeUIView(context: Context) -> SCNView {
scene.physicsWorld.contactDelegate = context.coordinator
view.delegate = context.coordinator
return view
}
}
这是 SwiftUI 类
struct Game: View {
var view = FirstClass()
var body: some View {
ZStack {
view
...
}
}
}
这部分
let secondClass = SecondClass()
不起作用,因为SwiftUI不知道SecondClass
的实例,以便正确管理其生命周期。更多,您似乎没有使用 view
结构的 SecondClass
属性(顺便说一句,结构的有趣名称:))
一种解决方案是在同一个
UIViewRepresentable
内管理两个场景,基本上将生命周期管理保持在同一侧。
struct MyScene : UIViewRepresentable {
var view = SCNView()
var firstScene = SCNScene(named: "First.scn")!
lazy var secondScene = SCNScene(named: "Second.scn")!
...
/// Transitions into the second scene.
func changeScenes() {
controlManager.jumped = false
let transition = SKTransition.fade(with: .black, duration: 0.5)
view.present(secondScene, with: transition, incomingPointOfView: nil)
}
}