I am currently working on implementing collision detection for the meshes in my Three.js scene. I find myself confused about the functionality of the Raycaster and if I am using it correctly.
Below is a fiddle that illustrates the issue I am facing:
// Adding a cube at 40/40
geometry = new THREE.CubeGeometry(20, 20, 20);
material = new THREE.MeshNormalMaterial();
mesh = new THREE.Mesh(geometry, material);
mesh.position.setY(40)
scene.add(mesh);
// Adding Ray
var origin = new THREE.Vector3(50, 0, 0),
direction = new THREE.Vector3(-1,0,0),
ray = new THREE.Raycaster(origin, direction),
collisionResults = ray.intersectObjects([mesh]);
if(collisionResults.length!==0){
alert('Ray collides with mesh. Distance :' + collisionResults[0].distance)
}
// Adding Arrow to show ray
scene.add( new THREE.ArrowHelper(direction, origin, 50, 0x000000));
Not working: http://jsfiddle.net/FredricBerling/LwfPL/1/
Working: http://jsfiddle.net/FredricBerling/LwfPL/3/
The fiddle demonstrates creating a cube and shooting a ray from the point (50,0,0) in a specific direction. However, there seems to be an issue where the collision is detected even when it shouldn't be.
An Arrowhelper is added to visually represent the direction in which the Raycaster shoots its ray.
Upon further testing, it appears that the direction in the Raycaster differs from the one in the Arrowhelper. The Raycaster seems to shoot the ray towards the origin of the scene (0,0,0), causing confusion.
EDIT: Thanks to Rob's suggestion, I have realized the importance of rendering the meshes to ensure that world matrices are properly applied. The fiddle has been updated with the corrected code that now functions as expected for testing the Raycaster behavior.