Modifying object colors on hover using three.js

As a beginner in the world of Three.js and WebGL, my first project involves creating a model of an animal and animating it in different ways, such as having its head follow the mouse cursor. The model consists of various geometries that are combined in separate functions. Here is an example of one such function:

var BodyFunc = function(){
this.mesh = new THREE.Object3D();
this.mesh.name = "body";

// Code for body geometry goes here...

These functions are then called within a master createAnimal() function to assemble the complete creature:

function createAnimal(){

// Code for assembling the animal components goes here...

}

I shared this code structure because I suspect it may not be the most efficient way to achieve what I want with the model. Now onto the issue at hand...

The Problem Statement

I am trying to make the Bottom Body section (BodyBottom) change color when hovered over, but currently, only the shadow cast by the animalGroup changes color. I believe using raycasting is the solution, but I'm facing difficulties with detecting individual objects or even the entire animalGroup. I have set up a detectMouseMove event listener to get the 3D position of the mouse, like so:

// Code for getting mouse position in 3D goes here...

I have also implemented raycasting based on a Three.js example inside the detectMouseMove function:

// Raycasting code snippet...

However, this raycasting seems to only affect the shadow of the Animal object, not the actual body parts. Furthermore, changing the floor shader's color demonstrates this more clearly.

My assumption is that due to the construction or invocation of the animal model, the raycaster is failing to intersect with it. But I'm unsure, which is why I seek guidance here.

Resolution Needed:

  • Fix to allow individual objects to be recognizable by the raycaster
  • Ensure only the BodyBottom part is selectable via raycasting

Thank you for your assistance. Feel free to ask for additional code examples if necessary. This being my debut question on SO, I welcome constructive feedback on how to enhance future inquiries. Much appreciated!

Answer №1

It turns out that a simple change was all it took to fix my issue:

I had to swap this line of code:
var intersects = raycaster.intersectObjects( scene.children );

for this one:

var intersects = raycaster.intersectObjects( scene.children, true );

Big thanks to @WestLangley for providing the solution in the comments section of my original question. I'm sharing it here so that anyone who comes across this problem in the future can benefit from the clear answer.

Further research led me to discover that adding the true parameter makes the intersection recursive, allowing it to intersect all nested objects within the main object. In my case, grouping all objects under a single parent "master" group required this recursive feature to work properly. However, the reason why changing this setting only affected the color of the shadow and not the entire animal remains unclear to me. Please share your thoughts on this in the comments section. For more detailed information, refer to the documentation here.

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

Switch between light and dark modes with the MUI theme toggle in the header (AppBar)

I'm currently working on implementing a feature that allows users to switch between dark and light themes in my web app. The challenge I am facing is how to ensure that this theme change functionality is available throughout the entire app, not just i ...

Adjust the background color using jQuery to its original hue

While working on a webpage, I am implementing a menu that changes its background color upon being clicked using jQuery. Currently, my focus is on refining the functionality of the menu itself. However, I've encountered an issue - once I click on a men ...

Should property paths be shortened by utilizing new variables for better organization?

Yesterday, someone asked me why I would introduce a variable to shorten the property path. My answer was simply that it feels easier to read. Now I am curious if there are any objective reasons to choose between the two options listed below (such as memory ...

Ways to retrieve and upload a blob from a file object

After receiving a file object via an HTML input on-change event in my component.html: onFileSelected(event) { this.selectedFile = event.target.files[0]; } Now, I need to send a POST request to upload the image to the database. The database only acc ...

Determining Velocity of an Object in Three.js

Can anyone help me figure out how to calculate an object's velocity in three.js? I've checked the Object3D documentation but can't seem to find anything related to velocity. Appreciate any assistance, ...

The button should only be visible when the input is selected, but it should vanish when a different button within the form is

Having an issue with displaying a button when an input field is in focus. The "Cancel" button should appear when a user interacts with a search bar. I initially used addEventListener for input click/focus to achieve this, but ran into a problem: on mobile ...

Is there a way to convert my function into a variable in order to execute an array of statements

I'm struggling to convert this code into a variable. I need to bind it inside a statement execute array. This is the code I am working on, which retrieves the current date and timezone. I attempted using $date = function() {}, echo $date(); but that ...

React/Redux - Issue with rest operator functionality in component

Here is the initial state I am working with: const initialState = { selectedGroup: {}, groups: { rows: [], total: null }, offset: 0, range: 15, loading: false, error: null } Within a reducer function, I have this case for successful ...

javascript utilize jquery to advance saved event

When it comes to hyperlinks, I am pausing some of my native click events to verify if the resulting page contains the desired content. After storing the jquery event object and performing some validations, my goal is to allow the event to continue as usua ...

Can AJAX function properly when the server-side code is hosted on a separate domain?

After opening Firefox's scratchpad and inputting the following code... function ajaxRequest() { var xmlhttp; var domainName = location.host; var url = 'http://leke.dyndns.org/cgi/dn2ipa/resolve-dns.py?domainName='; url = url + domainName + ...

Unable to change placeholder in Material UI's Select Form

I'm having trouble modifying my SelectionForm. I need to update the color of the placeHolder image from red to a different color, but I can't find any properties or props on the material ui Docs to do so. Can someone assist me with this? https:/ ...

Sort the results by total count in Mongoose Express Node.js after grouping by id

I have a unique collection of items: { "_id": { "$oid": "5f54b3333367b91bd09f4485" }, "items": [ { "_id": 20, "name": "Turkish Coffee", "price": ...

Encountering an issue while constructing an Angular library project. The 'ng serve' command runs smoothly on local environment, but an error message stating

I recently developed an npm package called Cloudee. While it functions perfectly locally, I encounter an issue when attempting to deploy it. The error message states: 'Unexpected value 'CloudyModule in /home/hadi/dev/rickithadi/node_modules/cloud ...

The $scope within the $ionicplatform is not functioning as expected

I've been working on an application, but it doesn't seem to be functioning correctly. Typically, when we add a value to the scope, I expect it to update in the application. Here is the snippet from index.html: <body ng-app="starter"> <i ...

Creating a basic bar graph using d3.js with an array of input data

In my dataset, I have an array of form data that includes items like 'Male', 'Female', 'Prefer Not To Say'. I want to create a simple bar chart generator using D3.js that can display the percentages or counts of each item in t ...

What steps can I take to address this Material UI alert and deliver a solution that adds value?

I am currently working on fetching API data (specifically category names) from the back-end (Node.js) to the front-end (React). My main objective right now is to populate a Select component from Material UI. To fetch the API data, I am utilizing Express an ...

Overuse of jQuery's preventDefault() and stopPropagation() functions

A recent discussion with a coworker revealed some contrasting coding practices, mainly concerning his extensive use of the two aforementioned methods in event handlers. Every event handler he creates follows this same pattern... $('span.whatever&apos ...

What is the reason why the show() function in JQuery only applies to one specific element, rather than all elements selected with the same selector?

JSFiddle. This example code features a nested <table> within another <table>. The main issue concerns the click listener for the #add button. Specifically, the final if/else statement in the function. When you execute this code and click the ...

Styling a Pie or Doughnut Chart with CSS

I am working on creating a doughnut chart with rounded segments using Recharts, and I want it to end up looking similar to this: Although I have come close to achieving the desired result, I am encountering some issues: Firstly, the first segment is over ...

Downloading Files Using Ajax and Javascript

When a client makes a request through XMLHttpRequest, the information is sent to the server. The server compiles a CSV file and sends it back as the output stream of the response to the client. Next, the client's browser should display a download dia ...