Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js ray casting for particular Points

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!

like image 726
duhaime Avatar asked Jul 09 '17 18:07

duhaime


1 Answers

In the process of typing out the question above, I realized that the raycaster.params.Points.threshold = 20; line was setting a threshold for my Points that was much larger than the Points themselves were:

pointMaterial = new THREE.PointsMaterial({
  size: 6,
  vertexColors: THREE.VertexColors
});

I decreased the raycaster.params.Points.threshold value to 5 and now the hovering seems to be picking up the right points.

like image 123
duhaime Avatar answered Oct 21 '22 16:10

duhaime