Applying Physics on USDZ model in RealityKit

670 Views Asked by At

I'm trying to load Entity from a USDZ file and then apply physics to its ModelEntity

I'm using toy_robot_vintage model from Apple's gallery. It contains an animation that I want to use, hence I'm loading the Entity. I figured out, I can't add physics to Entity because it does not conform to the HasPhysicsBody, so I get the vintage_robot_animRig_model_body and apply the PhysicsBodyComponent on it. However, it's not working. Which ModelEntity should I apply physics to and how should applying physics to different ModelEntity in hierarchy should reflect on my model?

I also tried to add a custom Entity subclass that conforms to the protocol, but after I create an object, I don't see it conforms to it.

This is what I have so far:

let modelEntity = robotEntity.findEntity(named: "vintage_robot_animRig_model_body")
let physics = PhysicsBodyComponent(massProperties: .default, material: .default, mode: .dynamic)   
modelEntity?.components.set(physics)
1

There are 1 best solutions below

1
On BEST ANSWER

Use generateCollisionShapes() instance method to activate physics and run collisions detection:

func makeUIView(context: Context) -> ARView {
    
    let arView = ARView(frame: .zero)
    
    let robot = try! Entity.loadAnchor(named: "robot")
    robot.scale = [0.03, 0.03, 0.03]
    let headEntity = robot.findEntity(named: "vintage_robot_animRig_model_head")
    
    robot.generateCollisionShapes(recursive: true)
    
    let physics = PhysicsBodyComponent(massProperties: .default, 
                                             material: .default, 
                                                 mode: .dynamic)
    headEntity?.components.set(physics)
    arView.scene.anchors.append(robot)
    
    return arView
}