ios - 当状态更改时,如何防止 SceneKit 场景重新渲染不佳?

标签 ios swift swiftui scenekit

我的父 View 有一个包含 SceneKit 场景的 subview ,但是当父 View 中发生任何状态更改时,它会重置 SceneKit 动画,更改模型的纹理,并使模型更大。

有没有办法让 SceneKit 场景不受状态变化的影响?

Image of the model before and after the state changes

这是父 View 的代码:

struct ContentView: View {
    @State private var color: Color = .sBlue

    var body: some View {
        VStack {
            Button(action: { self.color = .sOrange }) {
               self.color
            }
            .frame(height: 240)

            ModelView()
        }
    }
}

这是 SceneKit View 的代码:
struct ModelView: UIViewRepresentable {
    let model = SCNScene(named: "art.scnassets/3D Models/yBotIdle.scn")!

    func makeUIView(context: Context) -> SCNView {
        model.rootNode.childNode(withName: "yBot", recursively: true)?
            .scale = SCNVector3(x: 0.03, y: 0.03, z: 0.03)

        let cameraNode = SCNNode()
        let camera = SCNCamera()
        camera.focalLength = 120
        cameraNode.camera = camera
        cameraNode.position = SCNVector3(x: 0, y: 2.8, z: 35)
        model.rootNode.addChildNode(cameraNode)

        let directionalLightNode = SCNNode()
        directionalLightNode.light = SCNLight()
        directionalLightNode.light?.type = SCNLight.LightType.directional
        directionalLightNode.light?.intensity = 1500
        directionalLightNode.position = SCNVector3(x: 0, y: 6, z: 10)
        directionalLightNode.eulerAngles = SCNVector3(x: -0.4, y: 0, z: 0)
        model.rootNode.addChildNode(directionalLightNode)

        let modelView = SCNView()
        modelView.antialiasingMode = SCNAntialiasingMode.multisampling4X
        modelView.backgroundColor = UIColor(ciColor: .clear)

        return modelView
    }

    func updateUIView(_ modelView: SCNView, context: Context) {
        modelView.scene = model
    }
}

谢谢!

最佳答案

弄清楚了!创建 SceneKit View 的实例以在父 View 中使用而不是直接使用 SceneKit View 可以解决这些问题。我不确定为什么会这样,如果有人能解释我很想听听。

struct ContentView: View {
    @State private var color: Color = .sBlue
    let modelView = ModelView()

    var body: some View {
        VStack {
            Button(action: { self.color = .sOrange }) {
                self.color
            }
            .frame(height: 240)

            modelView
        }
    }
}

关于ios - 当状态更改时,如何防止 SceneKit 场景重新渲染不佳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61925217/

相关文章:

ios - Grand Central Dispatch 和单元测试

ios - 使用自定义类以编程方式创建 UIView (Swift 4)

iphone - 在 AVFoundation 中使用不同的分辨率预设

ios - 应用程序在某些 iPhone 上显示错误的语言

ios - 将 TextView 限制为 swift 2 中的特定行数

swift - 如何在SwiftUI中使用.refreshable调用API并刷新列表

SwiftUI:发布自定义形状的更新

SwiftUI ObservableObject 在发布值时不会更新

iOS 如何从 url 打开应用程序或重定向到应用程序商店以下载应用程序

swift - 如何使用 UINavigationController 的 searchController 属性将 UISearchController 合并到 SwiftUI NavigationView 中?