Search code examples
three.jscameraintersectionraytracing

Ray intersection and child camera


I've been playing with three.js for few weeks now and got few inconsistencies on ray casting. Here is a simplified version demonstrating one of the bug I encoutered :

http://jsfiddle.net/eMrhb/12/

The camera is added to the sphere mesh for further use of TrackBallControl for example.

scene.add(mesh);    
mesh.add(camera);

Clicking a few times on the sphere and opening the console, show us none of the expected intersections between the ray and the mesh.

Adding the camera to the scene (http://jsfiddle.net/eMrhb/9/), solves the problem:

scene.add(mesh);    
scene.add(camera);

But I could use a much more complex hierarchy between my scene objects and the camera to suit my needs.

Is this a limitation? If it is, is there any workarounds I could use?


Solution

  • Yes, this is fixable.

    If the camera is a child of another object that is rotated and or translated, then your have to use a different pattern in ray casting.

    Instead of this familiar pattern:

    var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
    

    You have to use this pattern instead:

    var position = camera.matrixWorld.getPosition().clone();
    var ray = new THREE.Ray( position, vector.subSelf( position ).normalize() );
    

    three.js r.53