RealityKit: Scale generalText based on distance from Anchor

I would like to make text change size as I move towards/away from the image anchor I created.
  • as I move towards the image, the text gets smaller

  • as I move away from the image, the gets bigger

My current function to create the text is below:
Code Block
func addTitleToAnchor(text:String, color:SimpleMaterial.Color, isMetallic:Bool, anchor: AnchorEntity, height: Float) {
  let mesh = MeshResource.generateText(
        text,
        extrusionDepth: 0.02,
        font: .init(descriptor: .init(name: "Helvetica", size: 1), size: 1),
        containerFrame: .zero,
        alignment: .center,
        lineBreakMode: .byWordWrapping)
  let material = SimpleMaterial(color: color, isMetallic: isMetallic)
  let entity = ModelEntity(mesh: mesh, materials: [material])
  entity.name = "title"
  entity.setScale(SIMD3<Float>(0.015 ,0.015,0.015), relativeTo: anchor)
  anchor.addChild(entity)
  entity.setPosition(SIMD3<Float>(-0.05, 0.03, -height), relativeTo: anchor)
  entity.transform.rotation = simd_quatf(angle: -.pi/2, axis: [1,0,0])
  return
}

Hey there LT13,

You will need to enforce this constraint when you receive the scene update event. (i.e. SceneEvents.Update).

Code Block
arView.scene.subscribe(to: SceneEvents.Update.self) { updateEvent in
            /* Do something when the Update event is received (i.e. once per frame) */
        }.store(in: &subscriptions)


When you receive the update event, you should check your distance to the image, calculate a scale factor based on this distance, and then update your entity's text mesh based on the new scale factor.
Hey LT13 -

I had to do something similar recently, and I solved it by checking the distance from the camera to my entity in the session delegate didUpdate function, and setting the scale based on the distance. Please consider the following example below:

Code Block
func session(_ session: ARSession, didUpdate frame: ARFrame) {
  for entity in self.arView.scene.anchors {
    if case let AnchoringComponent.Target.world(transform) = entity.anchoring.target {
      let distance = distance(transform.columns.3, frame.camera.transform.columns.3)
      entity.scale = .one * (4 * sqrtf(distance))
    }
  }
}

You can change the entity.scale formula to work however you'd like. For me, it sets an initial scale for the entity and will scale it relative to the distance between the camera and the entity.
RealityKit: Scale generalText based on distance from Anchor
 
 
Q