Lab 008 – Anchor and entity to the head

Create a tracked entity that will update based on head position, then child an entity to it.

In Lab 007 we looked at hand anchors, now let’s take a look at the head anchor. This simple scene will create a sphere with an emoji inside that will be attached to the users head. The anchor itself is at the same coordinates as the users head, so we need to offset the position of our entity so the user can use it. In this case I placed it 1.5 units directly in front of the user.

struct Lab008: View {

    // 1. Create an entity that will be anchored to the head
    @State var headTrackedEntity: Entity = {
        let headAnchor = AnchorEntity(.head)
        return headAnchor
    }()

    var body: some View {
        RealityView { content, attachments in

            // 2. Create a model to attach to the tracked entity
            // Set the Z position to push the model away from the user
            let model = ModelEntity(
                mesh: .generateSphere(radius: 0.1),
                materials: [SimpleMaterial(color: .black, isMetallic: false)])
            model.position = SIMD3(x: 0, y: 0, z: -1.5) // position the model in front of the user
            model.scale = SIMD3(x: -1, y: 1, z: 1) // flip this inside out

            // Bonus: add an attachment to the model
            if let attachmentEntity = attachments.entity(for: "AttachmentContent") {
                attachmentEntity.scale = .init(repeating: 2.0)
                attachmentEntity.components[BillboardComponent.self] = .init()
                model.addChild(attachmentEntity)
            }
            headTrackedEntity.addChild(model)

            // 3. Make sure to add the head tracked entity to the scene graph
            content.add(headTrackedEntity)

        } update: { content, attachments in
            //...
        } attachments: {
            Attachment(id: "AttachmentContent") {
                Text("👀")
                    .font(.extraLargeTitle2)
            }
        }
    }
}

Video demo

Video demo of a small character anchored to a users head in visionOS

Support our work so we can continue to bring you new examples and articles.

Download the Xcode project with this and many more labs from Step Into Vision.

Questions or feedback?