美文网首页
RealityKit实现摆件功能

RealityKit实现摆件功能

作者: 浪淘沙008 | 来源:发表于2022-09-22 17:08 被阅读0次

其中AR效果是通过RealityKit实现的,其主要代码如下

        self.view.insertSubview(arView, belowSubview: entitySelectView)
        let config = ARWorldTrackingConfiguration() // 设置世界坐标系
        config.planeDetection = .horizontal // 设置检测水平面
        self.arView.session.run(config)

将物品对象添加到平面上

    // 定位,确定释放点在世界坐标系中的位置
    let location = session.location(in: arView)
        guard let result = self.arView.raycast(from: location, allowing: .estimatedPlane, alignment: .horizontal).first else {
            return UIDropProposal(operation: .copy)
        }
     // 加载模型对象并生成锚点   
      @available(iOS 15.0, *)
    func loadEntity(name: String) -> ARAnchor? {
        guard let raycastResult = self.raycastResult else {
            return nil
        }
        let anchor = ARAnchor(name: name, transform: raycastResult.worldTransform)
        let robotAnchor = AnchorEntity(anchor: anchor)
        // 同步加载
        do {
            let myModelEntity = try ModelEntity.load(named: name)
            robotAnchor.addChild(myModelEntity)
            self.arView.scene.addAnchor(robotAnchor)
            activityEntity = myModelEntity
                // 设置执行可用动画
            if let _ = myModelEntity.availableAnimations.first {
                myModelEntity.playAnimation(myModelEntity.availableAnimations[0].repeat())
            }
        } catch {
            return nil
        }
        return anchor
    }

func addAchor() {
        let planeMesh = MeshResource.generatePlane(width: 0.01, height: 0.01, cornerRadius: 0.01)
        let planeEntity = ModelEntity(mesh: planeMesh, materials: [planeMaterial])
        planeEntity.generateCollisionShapes(recursive: false)
        planeAnchor = AnchorEntity()
        planeAnchor.addChild(planeEntity)
        self.arView.scene.addAnchor(planeAnchor)
}

效果图:


output.gif

相关文章

网友评论

      本文标题:RealityKit实现摆件功能

      本文链接:https://www.haomeiwen.com/subject/wqowortx.html