When playing video games, I often notice a common pattern where hovering the mouse over an object triggers a gradient highlight around its 2D representation. To recreate this effect in my Three.js scene, I started by setting up the necessary raycaster variables:
var projector = new THREE.Projector();
var mouse2D = new THREE.Vector2(0, 0);
var mouse3D = new THREE.Vector3(0, 0, 0);
Next, I implemented a raycaster function:
document.body.onmousemove = function highlightObject(event) {
mouse3D.x = mouse2D.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse3D.y = mouse2D.y = -(event.clientY / window.innerHeight) * 2 + 1;
mouse3D.z = 0.5;
projector.unprojectVector(mouse3D, camera);
var raycaster = new THREE.Raycaster(camera.position, mouse3D.sub(camera.position).normalize());
var intersects = raycaster.intersectObject(mesh);
if (intersects.length > 0) {
var obj = intersects[0].object; //the intersected object
rotate = false;
} else {
rotate = true;
}
}
With this code, I can determine which object the user is currently hovering over. But the question remains: how do I create an outline around that object?