RealityKit实现图片跟踪功能

RealityKit支持捕获跟踪现实中的图片的功能,可以通过ARReferenceObject.referenceObjects(inGroupNamed: 包名, bundle: Bundle.main)的方式来加载图片数组,但是这种方式对图片限制太多并且在多次尝试失败后找到了新的方法实现这一功能,并且可以通过加载网络图片来设置跟踪目标,代码如下:

import UIKit
import RealityKit
import ARKit

@available(iOS 15.0, *)
class ViewController: UIViewController, ARSessionDelegate {

    var arView: ARView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        arView = ARView(frame: .zero)
        let config = ARImageTrackingConfiguration()
        

        let trackedImagesLib1 = ARReferenceImage(UIImage(named: "anchor_img_01")!.cgImage!, orientation: .up, physicalWidth: 0.05)

        // 通过命名可以在获取锚点时确定是什么内容
        trackedImagesLib1.name = "萨瓦迪卡"
        
        config.trackingImages = [trackedImagesLib1]
        config.maximumNumberOfTrackedImages = 1
      
        self.view.addSubview(arView)
        arView.session.delegate = self
        arView.session.run(config, options: [])

    }


    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        arView.frame = self.view.frame
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        arView.session.pause()
    }

    func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
        guard let imageAnchor = anchors[0] as? ARImageAnchor else {
            return
        }
        
        DispatchQueue.main.async {
            do {
                let myModelEntity = try ModelEntity.load(named: "dance_girl")
                let objectAnchorEntity = AnchorEntity(anchor:imageAnchor)
                objectAnchorEntity.addChild(myModelEntity)
                objectAnchorEntity.scale = [0.03, 0.03, 0.03]
                self.arView.scene.addAnchor(objectAnchorEntity)
                if let animation = myModelEntity.availableAnimations.first {
                    myModelEntity.playAnimation(animation.repeat())
                }
                
            } catch {
                print("无法加载模型")
            }
        }
    }
}

效果图:

img.jpeg

你可能感兴趣的:(RealityKit实现图片跟踪功能)