12

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?

3

1 Answer 1

22

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

Sign up to request clarification or add additional context in comments.

2 Comments

Note: outlinePass.selectedObjects should be an array of selected objects... e.g. outlinePass.selectedObjects = [obj];
Not working for fbxLoader at all :( do you have any solution for the same?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.