Changing the material properties of an object using Raycaster in Three.js

I currently have a raycaster functioning well in Three.js.

Below is the code snippet responsible for defining the action to be taken when the cursor hovers over an object within 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) { // upon hovering over an object

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

}

Simply activating the object's opacity to 0.75 when hovered over by the user. Nonetheless, I am seeking a way to revert this opacity back to 1 once the cursor moves away from the object.

Could someone explain how I can achieve this using the raycaster? My initial thought was to establish a boolean that would turn false after the cursor is no longer hovering over the object, but referencing the object only seems possible during the hover state.

Answer №1

It is suggested to perform ray casting within the render function for optimal efficiency.

Make sure to track the current mouse position in the event handler onDocumentMouseMove.

function onDocumentMouseMove( event ){

    event.preventDefault();

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

Execute the ray casting logic in the render function and save the identified object in a variable. This enables you to adjust the .opacity property accordingly:

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;

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

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


    // [...]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating an MD5 hash for a UTF16LE string in Javascript (with no BOM and excluding 0-byte at the end) - Illustrated with a C#

I've been trying to figure out how to get an MD5 Hash of a UTF16-LE encoded string in JavaScript for the past few days. I have a method in C# as an example, but I'm not sure how to replicate it in JavaScript. Example: public string GetMD5Hash ( ...

Can other JavaScript event listeners be synchronized with an asynchronous event?

My goal is to manipulate a web page using Tampermonkey where there is a button with certain event listeners followed by a redirect. Is it possible for me to insert my own click event handler into the button, which triggers an AJAX request and waits for it ...

Calculation of time intervals based on input values from text boxes, calculating quarters of an hour

I am facing a couple of challenges: -I am trying to calculate the time duration in hours between two military times input by the user in two textboxes. The result should be in quarter-hour intervals like 2.25 hours, 2.75 hours, etc. -The current calculat ...

Incorporating a Three.js rendering into your design

I am currently working on incorporating a .jpg image into my 3D scene. Most solutions I have come across involve applying the images onto meshes as textures, but then the scene doesn't look very realistic. The mesh borders are visible, whether it&apos ...

Each element is being adorned with the Ajax success function class

Currently, I am in the process of creating an Ajax function to integrate search features into my project. The search function itself is functioning properly; however, within the success: function, I am encountering an issue. Specifically, I am attempting t ...

Compare the precise value of $(window).height() to a specific scroll value

Initially, I retrieve $(window).height() and compare this height with the specific scroll value. $(window).scroll(function (event) { var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); console.log("window hei ...

Changing the value in a URL String using JavaScript

I am in possession of a String that contains a URL resembling the following: var url ="http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jg ...

TypeScript Redux actions not returning expected type

Basically, I am attempting to assign types to a group of functions and then match them in my Redux reducer. Here are the functions I have defined in actions.ts: export const SET_CART_ITEMS = "SET_CART_ITEMS"; export const SET_CART_TOTALS = "SET_CART_TOTA ...

Alternative to updating object coordinates in Fabric JS 1.7.9 - seeking solutions for migration challenges

Update: JSFiddle: https://jsfiddle.net/Qanary/915fg6ka/ I am currently working on implementing the `curveText` function (found at the bottom of this post). It was functioning properly with `fabric.js 1.2.0`, but after updating to `fabric.js 1.7.9`, I not ...

Designing a calendar with a grid template

I am attempting to design a calendar that resembles an actual calendar, but I am facing an issue where all created divs (representing days) are being saved in the first cell. I am not sure how to resolve this. Any help would be greatly appreciated. css . ...

Learn how to implement a switch case statement in this function

I'm a beginner in PHP and JS. This function is used to retrieve only one value. In my program, the 'dept1' values are 5 where the first value is selected onchange in 1, the second value selected onchange in 2, and the third value selected on ...

Unraveling based on changing values in es6

Trying to retrieve query parameters from the frontend in my express endpoint. const { filterType1, filterType2 } = req.query However, the issue is that the filterType values are coming from a predefined list of array elements. const list = ['priceF ...

Is there a way for me to acquire the Amazon Fire TV Series?

I'm currently working on developing a web app for Amazon Fire TV, and I require individual authorization for each app. My plan is to utilize the Amazon Fire TV serial number for this purpose. However, I am unsure how to retrieve this serial using Jav ...

Struggling to access values from your model using EL in JavaScript? Let me provide some guidance

In my model, there is an object named "domain" with two methods: getDescriptionEn() and getDescriptionFr(). I am trying to retrieve the appropriate description based on the current locale. My issue lies in the following code snippet: var locale = "${cur ...

Ensure that the assistant stays beneath the cursor while moving it

I am currently working on creating a functionality similar to the 'Sortable Widget', but due to some constraints, I cannot use the premade widget. Instead, I am trying to replicate its features using draggable and droppable elements: $(".Element ...

Adjust the appearance of matSelect when the selection menu is activated

What is the best way to adjust mat-select properties when its options are open? <mat-select class="selector"> <mat-option><mat-option> </mat-select> .selector:focus { color: green; } I attempted using focus, but ...

Is it possible to eliminate the arrows from an input type while restricting the change to a specific component?

Is there a way to remove the arrows from my input field while still applying it only to the text fields within this component? <v-text-field class="inputPrice" type="number" v-model="$data._value" @change="send ...

Executing the JavaScript function only a single time is what you're looking

I'm having trouble getting this script to work correctly on my website. It is supposed to trigger an alert when the specified id is in the viewport, but the issue I am encountering is that the alert keeps popping up repeatedly while the id is still vi ...

Close the menu when clicking anywhere on the page body

I have successfully implemented a dropdown menu that opens when the navigation button is clicked. However, I am struggling to find a way to close the dropdown menu when the mouse clicks on any part of the page's body. If you have a solution for this ...

UI-router issue: UI view and links not functioning properly

Recently, I decided to implement ui-router for Angular in my project. After adding the following code snippet to my app module within the app.js file: angular .module("ngClassifieds", ['ngMaterial', 'ui.router']) .config(function($md ...