Search code examples
swiftarkitrealitykitreality-composer

Play animation when image anchor detected


In RealityKit I have an image anchor. When the image anchor is detected I would like to display an object and play animation it has. I created an animation in Reality Composer. It's a simple "Ease Out" animation which comes built-in Reality Composer.

Currently, my code looks like that:

struct ARViewContainer: UIViewRepresentable {

func makeUIView(context: Context) -> ARView {
    
    let arView = CustomARView(frame: .zero)

    // generate image anchor
    let anchor = AnchorEntity(.image(group: "AR Resources", name: "imageAnchor"))

    // load 3D model from Experience.rcproject file
    let box = try! Experience.loadBox()
    
    // add 3D model to anchor
    anchor.addChild(box)
    
    // add anchor to scene
    arView.scene.addAnchor(anchor)
    
    return arView
    
}

func updateUIView(_ uiView: ARView, context: Context) {}

}

Solution

  • The solution is easy. Choose Reality Composer's image anchor (supply it with a corresponding .jpg or .png image). Then assign a Custom Behavior for your model. As a trigger use a Scene Start. Then apply any desired Action.

    enter image description here


    Your code will be frighteningly simple:

    struct ARViewContainer: UIViewRepresentable {
        
        func makeUIView(context: Context) -> ARView {
            
            let arView = ARView(frame: .zero)
            let scene = try! Experience.loadCylinder()
            arView.scene.addAnchor(scene)
            return arView
        }
    
        func updateUIView(_ uiView: ARView, context: Context) { }
    }
    

    Action will be played automatically (immediately after the image anchor appears).