Search code examples
three.jscollision-detection

detect collision for child mesh for three.js


I have an Object3D (position 10, 0, 30) with a child mesh (local position 0, 0, 0) constructed with BoxGeometry (w: 20, h: 20, d: 20).

Now if a ray is casted with the origin (-10, 0, 0) and direction (1, 0, 0) and checked for intersection, it detected intersection (incorrectly as the object is not in the path).

Consider this code:

const THREE = require('three');
let obj = new THREE.Object3D();
let boxGeo = new THREE.BoxGeometry(20, 20, 20);
let mat = new THREE.MeshPhongMaterial();
let mesh = new THREE.Mesh(boxGeo, mat);
obj.add(mesh);
obj.position.set(10, 0, 30);
let raycaster = new THREE.Raycaster(new THREE.Vector3(-10, 0, 0), new THREE.Vector3(1, 0, 0));
let intersects = raycaster.intersectObject(obj, true);

The intersects array is of length 2 whereas, it should be on length 0.


Solution

  • In order for Raycaster to correctly determine child objects recursively, I had to call updateMatrixWorld() on the parent object before checking intersectionObject.