Home > Software design >  Adding CustomEntity to the Plane Anchor in RealityKit
Adding CustomEntity to the Plane Anchor in RealityKit

Time:04-12

I have implemented a simple custom entity as shown below:

class Box: Entity, HasModel, HasAnchoring {
        
    required init(color: UIColor) {            
        super.init()                    
        self.components[ModelComponent.self] = ModelComponent(mesh: MeshResource.generateBox(size: 0.3), 
                                                         materials: [SimpleMaterial(color: color, isMetallic: true)])
    }
    
    convenience init(color: UIColor, position: SIMD3<Float>) {
        self.init(color: color)
        self.position = position 
    }
    
    required init() {
        fatalError("init() has not been implemented")
    }
}

ContentView.swift

I try to add the Box entity to the anchor, defined by the horizontal plane.

func makeUIView(context: Context) -> ARView {
        
    let arView = ARView(frame: .zero)            
    let anchorEntity = AnchorEntity(plane: .horizontal)
        
    let box = Box(color: .red)
    anchorEntity.addChild(box)
    arView.scene.anchors.append(anchorEntity)
    return arView
}

But, the Box entity never appears to be resting on the horizontal plane. It always seems to be floating on the top. Why is that?

CodePudding user response:

To prevent world anchoring at [0, 0, 0], you don't need to conform to the HasAnchoring protocol:

class Box: Entity, HasModel {
    // content...
}

So, your AnchorEntity(plane: .horizontal) are now active.

  • Related