Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

outline a 3d object in three.js

In many video games, I see a pattern where, when you mouse over an object, it will show a nice gradient highlight around the 2D form of the object. I set up a fairly basic Three.js scene with a sphere in it

To begin, I set up my raycaster variables:

var projector = new THREE.Projector();
var mouse2D = new THREE.Vector2(0, 0);
var mouse3D = new THREE.Vector3(0, 0, 0);

Then I make a raycaster function

document.body.onmousemove = function highlightObject(event) {
    mouse3D.x = mouse2D.x = mouse2D.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse3D.y = mouse2D.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 object that was intersected
         rotate = false;
     } else {
         rotate = true;
     }
}

This will get me the OBJECT they are currently hovering hover. Now how would one actually make an outline around the object?

like image 365
corvid Avatar asked Oct 13 '14 13:10

corvid


1 Answers

You need to use OutlinePass in your coding.

Create outlinepass inside your init() function

outlinePass = new THREE.OutlinePass(new THREE.Vector2(window.innerWidth, window.innerHeight), scene, camera);
composer.addPass( outlinePass );

And then set the outline selected objects.

if (intersects.length > 0) {
    var obj = intersects[0].object; // the object that was intersected
    rotate = false;
    outlinePass.selectedObjects = obj;
} else {
    rotate = true;
}

Take a look at this example: https://threejs.org/examples/?q=out#webgl_postprocessing_outline

like image 194
selvarajmas Avatar answered Oct 29 '22 12:10

selvarajmas