How can I randomly place AR objects in the real world?

279 views Asked by At

So I want the user to be able to open the app and look around using the phones camera and see random Augmented Reality objects.

How would I go about randomly placing them?

Sorry for the noob question. I've seen a lot about creating a reference plane but I want this to be able to be used in many different places, without previous cataloging.

1

There are 1 answers

0
Andy Jazz On

if you want an automatic placement of models in RealityKit but without the help of raycasting and ARWorldMap, you'll at least need to activate plane detection. Paste this code into Swift Playgrounds on iPad to test it.

import UIKit
import RealityKit
import PlaygroundSupport

class ViewController: UIViewController {        
    let arView = ARView(frame: .zero)
    
    override func viewDidLoad() {
        super.viewDidLoad()            
        self.view = self.arView
        self.arView.cameraMode = .ar          
        self.feed()
    }        
    fileprivate func feed() {            
        let anchorA = AnchorEntity(plane: .horizontal)
        let anchorB = AnchorEntity(plane: .horizontal)
        let anchorC = AnchorEntity(plane: .horizontal)            
        let model = ModelEntity(mesh: .generateSphere(radius: 0.025))
        anchorA.addChild(model)
        arView.scene.anchors.append(anchorA)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            anchorB.addChild(model.clone(recursive: false))
            self.arView.scene.anchors.append(anchorB)
        }                
        DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
            anchorC.addChild(model.clone(recursive: false))
            self.arView.scene.anchors.append(anchorC)
        }
    }
}  
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = ViewController()