You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让RealityKit平面在相机移动及跟踪图像消失后保持固定?

问题:跟踪图像消失后平面锚定仍存在位移的优化方案

需求与问题概述

  • 核心需求:当跟踪图像从视野中消失时,显示一个平面,并将该平面固定在图像最后出现的位置,不再随设备移动而偏移
  • 当前问题:参考Stack Overflow问题《Keeping model anchored in place when a tracking image is hidden》的方案,将示例中的球体替换为平面实现后,平面仍无法完全固定:
    • 调用reanchor方法后,位移幅度有所减小,但仍存在明显的小幅偏移
    • 优化后的尝试代码仍未解决该问题,寻求更稳定的实现方案

初始实现代码

import ARKit
import RealityKit

class ViewController : UIViewController {

  @IBOutlet var arView: ARView!
  var anchorEntity = AnchorEntity(.image(group: "AR", name: "Image"))
  var planeEntity = ModelEntity()

  override func viewDidLoad() {
    super.viewDidLoad()

    arView.session.delegate = self

    // size of image referenced above
    let width = Float(0.2667)
    let height = Float(0.15001875)
    let mesh: MeshResource = .generatePlane(width: width, depth: height)
    let material = SimpleMaterial(color: .systemPink, isMetallic: false)
    self.planeEntity = ModelEntity(mesh: mesh, materials: [material])

    self.anchorEntity.addChild(planeEntity)
    arView.scene.anchors.append(self.anchorEntity)
  }
}

extension ViewController : ARSessionDelegate {

  func session(_ session: ARSession, didUpdate frame: ARFrame) {

    if anchorEntity.isActive {
      anchorEntity.reanchor(.world(transform: planeEntity.transform.matrix),
                      preservingWorldTransform: true)
    }
  }
}

优化尝试代码

class ViewController: UIViewController {

  @IBOutlet var arView: ARView!
  var anchorEntity = AnchorEntity()
  var planeEntity = ModelEntity()

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    arView.session.delegate = self

    guard let reference = ARReferenceImage.referenceImages(
      inGroupNamed: "AR",
      bundle: nil)
    else { return }

    let config = ARWorldTrackingConfiguration()
    config.detectionImages = reference
    config.maximumNumberOfTrackedImages = 1
    arView.session.run(config)

    let width = Float(0.2667)
    let height = Float(0.15001875)
    let mesh: MeshResource = .generatePlane(width: width, depth: height)
    let material = SimpleMaterial(color: .systemPink, isMetallic: false)
    self.planeEntity = ModelEntity(mesh: mesh, materials: [material])

    self.anchorEntity.addChild(planeEntity)
  }
}

extension ViewController: ARSessionDelegate {

  func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {

    guard let imageAnchor = anchors.first as? ARImageAnchor
    else { return }

    if imageAnchor.isTracked == false {
      arView.scene.anchors.append(self.anchorEntity)
      self.planeEntity.transform.matrix = imageAnchor.transform
      self.anchorEntity = AnchorEntity(anchor: imageAnchor)
    }
  }
}

内容的提问来源于stack exchange,提问作者janineanne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 05:45:00