1
votes

I have a raycaster already set up in Three.js, which works.

Here's the code that determines what happens when you mouse over an object in the scene:

function onDocumentMouseMove( event ){

  mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  mouse.y = -( event.clientY / window.innerHeight ) * 2 + 1;

  raycaster.setFromCamera( mouse, camera );

  if (intersects.length > 0) { // if an object has been moused over

       // set object to 75% opacity
       intersects[0].object.material.opacity = 0.75;
  }

}

All this does is set the object's opacity to 0.75 when the user places their cursor over the object. However, after the object is no longer moused over, I would like to reset the opacity back to 1.

How exactly would I do this with raycaster? I wanted to set up a boolean that becomes false after it is not moused over, but you can only reference the object when it is moused over.

1

1 Answers

1
votes

I recommend to dot the ray casting in the render function.

Notice the mouse current mouse position in the onDocumentMouseMove event

function onDocumentMouseMove( event ){

    event.preventDefault();

    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = -( event.clientY / window.innerHeight ) * 2 + 1;
}

Do the ray casting in the render function and store the found object in a variable. So you can reset the .opacity if the object is not further hit:

var intersectObject;

function render() {

    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObjects( scene.children );

    if (intersects.length > 0) {

        if (intersectObject != intersects[ 0 ].object) {

            // reset opacity
            if (intersectObject)
                intersectObject.material.opacity = 1.0;

            // notice new object
            intersectObject = intersects[ 0 ].object;
            // set object to 75% opacity
            intersectObject.material.opacity = 0.25;
            //intersectObject.material.color.setHex( 0xff0000 );
        }
    } else {

        // reset opacity
        if (intersectObject) {
            intersectObject.material.opacity = 1.0;
            intersectObject = null;
        }
    }


    // [...]
}