程序效果:
程序代码(您需创建两个文件)
文件1(MyApp):
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
Reality()
}
}
}
文件2(Reality):
import SwiftUI
import RealityKit
struct Reality: View {
var body: some View {
ARViewContainer().edgesIgnoringSafeArea(.all)
}
}
struct ARViewContainer: UIViewRepresentable {
func makeUIView(context: Context) -> ARView {
let arView = ARView(frame: .zero, cameraMode: .ar, automaticallyConfigureSession: true)
let anchorEntity = AnchorEntity(plane: .horizontal)//水平类场景
let box = MeshResource.generateBox(size: 0.2/2, cornerRadius: 0.05/5)//形状1 正方体
let sphere = MeshResource.generateSphere(radius: 0.2/4)//形状2 球
//还有Plane(平面)等
let material = SimpleMaterial(color: .blue, isMetallic: true)//颜色
let AR1entity = ModelEntity(mesh: box, materials: [material])//实体(加载形状1)
let AR2entity = ModelEntity(mesh: sphere, materials: [material])//实体(加载形状2)
AR2entity.position = simd_make_float3(0,0.2/2,0)//实体2的三维坐标
anchorEntity.addChild(AR1entity)//锚点1
anchorEntity.addChild(AR2entity)//锚点2
arView.scene.anchors.append(anchorEntity)//场景
return arView
}
func updateUIView(_ uiView: ARView, context: Context) {
}
}
备注:本节生成一个正方体和一个球体,然后展现他们。