Skip to content
On this page

ARKit增加一个盒子

体验一下ARKit的能力,在室内随便加点小球,然后在AR中显示出来。

效果如下图:

效果图

以下为操作流程。

新建项目

新建一个空项目,项目一定要选择 Augmented Reality App,能够省很多的事。

效果图

之后的 content technology 选择 realitykit。

效果图

其他代码如下

swift
import SwiftUI
import RealityKit
import ARKit

struct ContentView : View {
    @State var modelNames: String = ""
    @State var count: Int = 0
    
    var body: some View {
        ZStack {
            ARViewContainer(modelNames: $modelNames)
            
            HStack {
                Button {
                    count = count + 1
                    modelNames = "\(count)"
                    print("call click")
                } label: {
                    Text("增加 \(count)")
                        .frame(width: 120, height: 40)
                        .background(Color.black.opacity(0.4))
                        .cornerRadius(10)
                }
            }
        }
    }
}

struct ARViewContainer: UIViewRepresentable {
    @Binding var modelNames: String
    
    func makeUIView(context: Context) -> ARView {
        let arView = ARView(frame: .zero)
        
        let configuration = ARWorldTrackingConfiguration()
        configuration.planeDetection = [.horizontal, .vertical]
        arView.session.run(configuration)

        return arView
    }
    
    func updateUIView(_ uiView: ARView, context: Context) {
        print("update view")
        let mesh = MeshResource.generateBox(size: 0.1, cornerRadius: 0.005)
        let material = SimpleMaterial(color: .gray, roughness: 0.15, isMetallic: true)
        let model = ModelEntity(mesh: mesh, materials: [material])

        let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2)))
        anchor.children.append(model)

        uiView.scene.anchors.append(anchor)
    }
}

#Preview {
    ContentView()
}