I want to place a 3D Model from the local device on top of the reference image when it's recognized. To achieve this I have tried the following:
- Adding the reference image to the session configuration:
override func viewDidLoad() {
super.viewDidLoad()
arView.session.delegate = self
// Check if the device supports the AR experience
if (!ARConfiguration.isSupported) {
TLogger.shared.error_objc("Device does not support Augmented Reality")
return
}
guard let qrCodeReferenceImage = UIImage(named: "QRCode") else { return }
let detectionImages: Set<ARReferenceImage> = convertToReferenceImages([qrCodeReferenceImage])
let configuration = ARWorldTrackingConfiguration()
configuration.detectionImages = detectionImages
arView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
}
- Using the
ARSessionDelegate
to get notified when the reference image was detected and placing the 3D model at the same position as hisARImageAnchor
:
func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
for anchor in anchors {
guard let imageAnchor = anchor as? ARImageAnchor else { return }
let position = imageAnchor.transform
addEntity(self.localModelPath!, position)
}
}
func addEntity(_ modelPath: URL, _ position: float4x4) {
// Load 3D Object as Entity
let entity = try! Entity.load(contentsOf: modelPath)
// Create the Anchor which gets added to the AR Scene
let anchor = AnchorEntity(world: position)
anchor.addChild(entity)
anchor.transform.matrix = position
arView.scene.addAnchor(anchor)
}
However, whenever I try to place the anchor including my 3D model (the entity) at a specific position, it doesn't appear in the arView. It seems like the model is getting loaded though since a few frames are getting lost when executing the addEntity
function. When I don't specifically set the anchors position the model appears in front of the camera.
Can anyone lead me in the right direction here?