Search code examples
javascriptthree.jswebglcollision-detectionraycasting

threejs raycasting - intersections between camera and a loaded obj model


I'm moving a camera through a scene that contains an obj I've loaded as a mesh, and I want to detect if the camera has collided with any of the walls of my obj.

I've based my code off this threejs example: http://threejs.org/examples/misc_controls_pointerlock.html, and tried to apply your example here: http://stemkoski.github.io/Three.js/Collision-Detection.html - but I can't seem to get a collision.

My example is here

and the relevant javascript is here:

If anyone can point me in the right direction on how to detect a collision, I'd be grateful. Here's the relevant piece of code:

var objects = [];

var oLoader = new THREE.OBJLoader();
  //oLoader.load('models/chair.obj', function(object, materials) {
    oLoader.load('models/model-for-threejs.obj', function(object, materials) {

    // var material = new THREE.MeshFaceMaterial(materials);
    var material = new THREE.MeshLambertMaterial({ color: 0x000000 });
    //var material = new THREE.MeshBasicMaterial({wireframe: true});


    object.traverse( function(child) {
      if (child instanceof THREE.Mesh) {
        //objects.push(child); //MH - not sure if the object needs to be added here or not, but if I do, this really bogs down things down
      }
    });

    object.position.x = 0;
    object.position.y = 12;
    object.position.z = 0;

    scene.add(object);

    objects.push(object);


  });
}

var curPos = controls.getObject().position; //gives the position of my camera

    raycaster.ray.origin.copy( curPos );
    //raycaster.ray.origin.y -= 10; 
    raycaster.ray.origin.z +=10; //guessing here, but since I'm moving in 2d space (z / x), maybe I should be moving my ray ahead in z space?


    var intersections = raycaster.intersectObjects( objects ); //

    var isOnObject = intersections.length > 0;

    if (isOnObject){ console.log('collide' }; //MH - nothing happening here

Solution

  • Raycaster's intersect object takes an Object3D with children, and has a flag for recursion.

    https://github.com/mrdoob/three.js/blob/master/src/core/Raycaster.js#L33

    So it should look like this:

    var intersections = raycaster.intersectObjects( yourRootObject3D, true );