2

I am trying to attach a sphere at the center of the device screen and as I move the device around the sphere should stay in the centre of the screen (like a crosshair)

I have attached a sphere entity and added it to sphere_anchor like this in makeUIView function sphere_anchor.addChild(modelEntity)

But as i move my device the sphere just moves in the initial frame the entity was attached to as I move the device.Hoping someone could point me to the correct way of doing this

//Implement ARSession didUpdate session delegate method
public func session(_ session: ARSession, didUpdate frame: ARFrame) {
    
    let trasnform =  frame.camera.transform

    if ((self.scene.findEntity(named: "sphere")) != nil) {
        let position = simd_make_float3(trasnform.columns.3)
             //print(position)
         sphere_anchor.position = position
         sphere_anchor.orientation = Transform(matrix: trasnform).rotation
    }
}
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
anahom
  • 69
  • 4

1 Answers1

3

Try AnchorEntity(.camera). If you implement it there's no need for session(_:didUpdate:) instance method because RealityKit's anchor automatically tracks ARCamera position.

@IBOutlet var arView: ARView!

override func viewDidLoad() {
    super.viewDidLoad()
    
    let mesh = MeshResource.generateSphere(radius: 0.1)
    let sphere = ModelEntity(mesh: mesh)

    let anchor = AnchorEntity(.camera)

    sphere.setParent(anchor)
    arView.scene.addAnchor(anchor)
    
    sphere.transform.translation.z = -0.75
}

AnchorEntity(.camera) works only when real iOS device in Active Scheme is chosen.

enter image description here

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
  • 1
    I didn't know if I should ask a new ques, since it relates to the above answer- I wish to do a raycast from the position of the sphere to check if it intersects with any AR objects in the scene. (Much like if a crosshair was on top of any object in the scene) To use raycast I need the 2D position of the sphere in the view’s coordinate system. I understand the `project(SIMD3) -> CGPoint?` method converts the 3D world coordinate system of the scene to the 2D pixel coordinate and not the normalised view coordinates. Is there a way to do the above or this is an incorrect approach – anahom Jan 20 '21 at 14:02
  • @anahom, publish it as another question, please. – Andy Jazz Jan 20 '21 at 15:31
  • 1
    Hello, I posted a new question as suggested https://stackoverflow.com/questions/65814249/implement-a-crosshair-kind-behaviour-in-arkit – anahom Jan 20 '21 at 17:10