I've tried to give a physicsBodyComponet to modelEntity, and It just falls deep down

Viewed 255

On reality kit, I've tried to give a physicsBodyComponent to a modelEntity.

But as I put to modelEntity to real world, It just fall down.

Is there anyway to fix this?

1 Answers

You need to create a floor mesh with a PhysicsBodyComponent:

let floor = ModelEntity(mesh: .generateBox(size: [1000, 0, 1000]), materials: [SimpleMaterial()])
floor.generateCollisionShapes(recursive: true)
if let collisionComponent = floor.components[CollisionComponent] as? CollisionComponent {
    floor.components[PhysicsBodyComponent] = PhysicsBodyComponent(shapes: collisionComponent.shapes, mass: 0, material: nil, mode: .static)
    floor.components[ModelComponent] = nil // make the floor invisible
}
scene?.addChild(floor)

Then, when you load your entities, you also give them a PhysicsBodyComponent (and they need a non-zero mass, otherwise they will anyways fall through, which is what eluded me for a long time):

var loadModelCancellable: AnyCancellable? = nil
loadModelCancellable = Entity.loadModelAsync(named: modelUri)
  .sink(receiveCompletion: { _ in
      loadModelCancellable?.cancel()
  }, receiveValue: { entity in
      entity.generateCollisionShapes(recursive: true)

      if let collisionComponent = entity.components[CollisionComponent] as? CollisionComponent {
          entity.components[PhysicsBodyComponent] = PhysicsBodyComponent(shapes: collisionComponent.shapes, mass: 1, material: nil, mode: .dynamic)
      }

      scene.addChild(entity)
      loadModelCancellable?.cancel()
  })

In the end, adding physics to my project had too many unintended consequences for what I was trying to do (just preventing models to overlap), like models pushing each other, and movements needing to be redone completely, ... So I didn't get further than this, but at least this should let you add physics to your models without them falling indefinitely from gravity.

Related