如何使用RealityKit获取Swift中被跟踪图片的名称?

How to get the name of the tracked image in Swift with RealityKit?

我有多个 AR 参考图像,我想知道我当前正在跟踪哪一个。我怎样才能做到这一点?这是我的代码:

let configuration = ARImageTrackingConfiguration()

guard let trackedImages = ARReferenceImage.referenceImages(inGroupNamed: "Photos", bundle: Bundle.main) else {
      print("No images available")
      return
  }
    
  configuration.trackingImages = trackedImages
  configuration.maximumNumberOfTrackedImages = 1
  sceneView.session.run(configuration)

您需要使用 renderer(_:didAdd:for:) 方法。当您的应用检测到它识别的图像时,它会添加一个锚点。您可以从资产目录中提取该图像的名称。

将此添加到您的 ARSCNViewDelegate class:

func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
    guard let imageAnchor = anchor as? ARImageAnchor else { return }
    let image = imageAnchor.referenceImage
    // this is one means of getting the name of the image
    if let trackedImage = image.name {
        print(trackedImage)
    }
}

如果您需要 RealityKit 的解决方案,而不是 SceneKit 的解决方案,请使用以下代码:

import ARKit
import RealityKit

extension ViewController: ARSessionDelegate {
    
    func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
        
        guard let imageAnchor = anchors.first as? ARImageAnchor,
              let name = imageAnchor.referenceImage.name
        else { return }

        print(name)
        
        let entity = ModelEntity(mesh: .generateSphere(radius: 0.05))
        let anchor = AnchorEntity(anchor: imageAnchor)
        
        anchor.addChild(entity)
        arView.scene.anchors.append(anchor)
    }
}

不要忘记实现会话委托:

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        arView.session.delegate = self
    }
}