I'm working on a network visualization using Three.js and am having trouble determining why my ray casting implementation is not identifying the correct points (Full example and source).
More specifically, I'm trying to use ray casting with a Points cloud, and am attempting to change the color of a point to white once users hover on the point. Right now, hovering points does change the color of points, but the event seems to be triggered on points near the cursor rather than immediately below the cursor.
Here is the code I'm using to initialize the ray caster:
// configure the raycaster
raycaster = new THREE.Raycaster();
raycaster.params.Points.threshold = 20;
Here is the render function:
function render() {
renderer.render(scene, camera);
controls.update();
raycast();
}
// Color hovered points
function raycast() {
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObject(particles);
if (intersects.length) {
var newColor = new THREE.Color();
newColor.setRGB( 1, 1, 1 );
var index = intersects[0].index;
particles.geometry.colors[index] = newColor;
particles.geometry.colorsNeedUpdate=true;
}
}
And finally, the callback to the mousemove
event triggered on the body:
/**
* Mouse coordinates go from 0 to container width {0:1}
* and 0 to container height {0:1}. Multiply by 2
* and subtract 1 to center the mouse coords {-1:1}.
* Furthermore, negate the y axis coords, as in the DOM
* the origin is in the top left corner, while in WebGL
* the origin is in the bottom left corner.
**/
function onDocumentMousemove(e) {
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
Does anyone know why this code doesn't highlight the right points when users mouse around? Any insights would be very helpful!