Search code examples
swiftarkitrealitykit

How to activate RealityKit gestures for Model entity?


In the code below, I create a model entity and load a 3d model named "stone". I then set generateCollisionShapes to true. I should then be able to install gestures to the view but I'm getting an error saying my model entity doesn't conform to the type 'HasCollision'.

I need some help getting this to work. Any feedback is appreciated.

import ARKit
import RealityKit

class Coordinator: NSObject {
    
    weak var view: ARView?
            
    @objc func handleTap(_ recognizer: UITapGestureRecognizer) {

        guard let view = self.view else { return }            
        let tapLocation = recognizer.location(in: view)
        
        let results = view.raycast(from: tapLocation, 
                               allowing: .estimatedPlane, 
                              alignment: .horizontal)
        
        if let result = results.first {
            
            let anchor = AnchorEntity(raycastResult: result)
            
            guard let modelEntity = try? ModelEntity.load(named: "stone") 
            else {
                print("didn't find model")
                return
            }                
            modelEntity.generateCollisionShapes(recursive: true)
            anchor.addChild(modelEntity)                
            view.scene.addAnchor(anchor)                                
            view.installGestures(.all, for: modelEntity)    
        }            
    }        
}

Solution

  • You should use Entity.loadModel(...) method instead of ModelEntity.load(...)

    guard let modelEntity = try? Entity.loadModel(named: "stone") else { return }
    
    modelEntity.generateCollisionShapes(recursive: true)
    
    arView.installGestures([.all], for: modelEntity as Entity & HasCollision)
    

    P. S.

    • It's not good to declare an ARView object as UIView's view – declare it as arView.