Home > Blockchain >  RealityKit – Get ModelEntity Size as SIMD3<Float>
RealityKit – Get ModelEntity Size as SIMD3<Float>

Time:05-08

Is there anyway to know the size of the ModelEntity as SIMD3? Once, I get the size, I want to pass it to the CollisionComponent.

 let box = ModelEntity(mesh: MeshResource.generateBox(size: 0.2), 
                  materials: [SimpleMaterial(color: .green, isMetallic: true)])
 box.position.y = 0.3 
 box.generateCollisionShapes(recursive: true)
 box.physicsBody = PhysicsBodyComponent(massProperties: .default, 
                                              material: .default, 
                                                  mode: .dynamic)
            
 // I know I can use the following
 box.collision = CollisionComponent(shapes: [.generateBox(size: [0.2,0.2,0.2])], 
                                                          mode: .trigger, 
                                                        filter: .sensor)
            
 // but why not just pass the size of the box I created earlier. 
 box.collision = CollisionComponent(shapes: [PASS BOX SIZE HERE], 
                                      mode: .trigger, 
                                    filter: .sensor)

CodePudding user response:

To calculate the size of a primitive, use the max and min values of its bounding box.

let box = ModelEntity(mesh: MeshResource.generateBox(width: 0.11, 
                                                    height: 0.23, 
                                                     depth: 0.45))
       
// "reverse engineering"

let width = (box.model?.mesh.bounds.max.x)! - (box.model?.mesh.bounds.min.x)!
let height = (box.model?.mesh.bounds.max.y)! - (box.model?.mesh.bounds.min.y)!
let depth = (box.model?.mesh.bounds.max.z)! - (box.model?.mesh.bounds.min.z)!
    
let boxSize: SIMD3<Float> = [width, height, depth]
    
print(boxSize)

// Result:

// SIMD3<Float>(0.11, 0.23, 0.45)

To calculate the size of any part of .usdz model use the following approach:

let car = try! ModelEntity.load(named: "car.usdz")

let carBody = car.children[0]..........children[0] as! ModelEntity

print((carBody.model?.mesh.bounds)!)
  • Related