TypeError: Cannot read properties of undefined (reading 'updateWorldMatrix')

130 Views Asked by At

I am not very skilled in ThreeJS.

I am trying to create bounding box to wrap a 3D model. The model is loaded well because I can see it on the scene

const loader = new GLTFLoader();
loader.load(
  modelsPath[ 0 ],
  ( gltf ) => {
    mesh = gltf.scene;
    mesh.visible = false;
    mesh.matrixAutoUpdate = false;
    scene.add( mesh );
    box1 = new THREE.Box3().setFromObject( mesh.asset );
    group.add( box1 );
  },
  null,
  function ( error ) {
    console.log( error );
  }
);

but when I use box1 = new THREE.Box3().setFromObject( mesh.asset ); I got the following error:

TypeError: Cannot read properties of undefined (reading 'updateWorldMatrix')
at Box3.expandByObject (Box3.js:160:1)

Do you have any idea?

2

There are 2 best solutions below

2
Łukasz D. Mastalerz On

Try this one

const loader = new GLTFLoader();
let mesh;
let bb;

loader.load("REACT.glb", (gltf) => {
  mesh = gltf.scene;
  scene.add(mesh);
  bb = new THREE.Box3().setFromObject(mesh);
  const boxHelper = new THREE.Box3Helper(bb, 0x00ff00);
  scene.add(boxHelper);
});

https://threejs.org/docs/#api/en/helpers/BoxHelper

and BTW how can you see mesh, when you set visibility property to mesh in false? O_o

 mesh.visible = false;
4
Nephelococcygia On

The Box3 is a Mathematical object and not a Object3D meaning it can't be added to a Scene object. The reference you are looking for is BoxHelper, as follow:

const box = new THREE.BoxHelper(model, 0xff0000);
scene.add(box);

Example