3

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
mheavers
  • 29,530
  • 58
  • 194
  • 315

1 Answers1

2

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 );
Flux
  • 626
  • 1
  • 6
  • 15
  • Thanks - even with the recursion it seems to not be working (definitely slowed things down though) - I must be doing something else wrong. It wasn't clear to me if the objloader defaults to creating an Object3D - could that be the problem? – mheavers Jan 26 '15 at 21:46
  • Recursive raycast can be expensive if you have many objects in your scene. You can filter that by giving it only a subset, or use smarter ways to filter such as spatial subdivision. I would use a line to check your raycast ray and draw that for debugging – Flux Jan 27 '15 at 04:57