swiftuiswiftui-zstackvisionos

ZStack z-index offset on visionOS with Model3D views


If I take a ZStack and add a bunch of Model3D views to it (to arrange them in 2D space), the ZStack will give each successive view an adjustment to the z-axis, such that they appear to be placed on different planes. Is there a way to disable this?


Solution

  • To place 3D models on the same Z-plane (in case that the pivot point of each model is in its center), use the same depth and alignment values for each Model3D view.

    import SwiftUI
    import RealityKit
    import RealityKitContent
    
    struct ContentView: View {  
        var body: some View {
            ZStack {
                Model3D(named: "Scene", bundle: realityKitContentBundle)
                    .frame(depth: 1.0, alignment: .center)
                
                Model3D(named: "Scene", bundle: realityKitContentBundle)
                    .frame(depth: 1.0, alignment: .center)
            }
        }
    }
    #Preview {
        ContentView()
    }