ARKit加载多个usdz模型文件并点击切换显示,解决切换卡顿

实现效果如上所示,可以点击模型切换显示,加入了特征点显示的debugOptions,所以界面上会显示很多特征点。刚开始的时候,因为没有预加载模型文件,导致点击切换的时候再加载,就会出现卡顿一下的现象,所以做了优化处理,程序刚启动,就加载所有的模型文件,后续切换就很顺畅了。

1.先在官网下载模型文件并导入到xcode中

2.运行代码

Swift 复制代码
import ARKit
import RealityKit
import SwiftUI

struct ContentView: View {
    let modelName = ["biplane", "drummertoy", "pancakes", "pegasus"]
    var modelMap: [String: ModelEntity] = [:]

    @State private var curModel: ModelEntity

    init() {
        print("init app")
        for model in modelName {
            let modelEntry = try! ModelEntity.loadModel(named: "\(model).usdz")
            self.modelMap[model] = modelEntry
        }
        self.curModel = self.modelMap[self.modelName.first!]!
    }

    var body: some View {
        VStack {
            ARViewContainer(curModel: $curModel)
            HStack {
                ForEach(modelName, id: \.self) {
                    model in
                    Image(model).resizable().frame(width: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/, height: /*@START_MENU_TOKEN@*/100/*@END_MENU_TOKEN@*/).onTapGesture {
                        print("click model: \(model)")
                        // 更新当前模型
                        curModel = self.modelMap[model]!
                    }
                }
            }.padding(.horizontal)
        }
        .edgesIgnoringSafeArea(.all)
    }
}

struct ARViewContainer: UIViewRepresentable {
    @Binding var curModel: ModelEntity

    func makeUIView(context: Context) -> ARView {
        let arView = ARView(frame: .zero)
        arView.debugOptions = .showFeaturePoints

        // 配置 AR 会话,启用平面检测
        let configuration = ARWorldTrackingConfiguration()
        // 启用水平面检测
        configuration.planeDetection = [.horizontal]
        arView.session.run(configuration)

        // 创建一个水平面锚点
        let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2)))

        // 加载usdz模型文件
        let modelEntry = curModel
        modelEntry.position = [0, 0, 0]
        modelEntry.scale = [0.01, 0.01, 0.01]
        anchor.addChild(modelEntry)

        // 创建一个灯光
        let light = PointLight()
        light.position = [0, 1, 0]
        anchor.addChild(light)

        // 将锚点添加到场景中
        arView.scene.anchors.append(anchor)

        // 添加触摸事件识别器
        let tapGestureRecognizer = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.handleTap(_:)))
        // 给arview添加动作识别
        arView.addGestureRecognizer(tapGestureRecognizer)

        return arView
    }

    func updateUIView(_ uiView: ARView, context: Context) {
        print("update ui view")
        // 删除之前的模型
        uiView.scene.anchors.removeAll()
        // 更新模型
        let modelEntry = curModel
        modelEntry.position = [0, 0, 0]
        modelEntry.scale = [0.01, 0.01, 0.01]
        let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2)))
        anchor.addChild(modelEntry)
        uiView.scene.anchors.append(anchor)
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator()
    }
}
相关推荐
2351616 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
Swift社区20 小时前
从 0 到 1 构建一个完整的 AGUI 前端项目的流程在 ESP32 上运行
前端·算法·职场和发展
Swift社区1 天前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
Espresso Macchiato1 天前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167
前端架构师-老李1 天前
面试问题—你接受加班吗?
面试·职场和发展
熬了夜的程序员1 天前
【LeetCode】69. x 的平方根
开发语言·算法·leetcode·职场和发展·动态规划
.NET修仙日记1 天前
2025年ASP.NETMVC面试题库全解析
面试·职场和发展·c#·asp.net·mvc·面试题·asp.net mvc
Swift社区1 天前
LeetCode 394. 字符串解码(Decode String)
算法·leetcode·职场和发展
tt5555555555552 天前
LeetCode进阶算法题解详解
算法·leetcode·职场和发展
我命由我123452 天前
Excel - Excel 列出一列中所有不重复数据
经验分享·学习·职场和发展·word·powerpoint·excel·职场发展