The feature to highlight an object on mouseover is not working as expected

My goal is to make objects stand out by changing their color when the mouse hovers over them, specifically a sphere. The issue I'm facing is that the highlighting works for the sphere, but then it seems stuck with it. When I hover over other objects, the color doesn't update as expected; it still reflects the original sphere's color.

To guide my implementation, I looked at the original Three.js example provided here: https://threejs.org/examples/#webgl_interactive_cubes

Naturally, I've removed most of the unnecessary code :)

export default {
name: 'ThreeTest',
data() {
  return {
    mouse: new THREE.Vector2(),
    rayCaster: new THREE.Raycaster(),
    spheres: [],
    intersectHighlighted: null,
    highlighted: null
  };
},
methods: {
  init() {

    //Map Creation:
    let map = document.getElementById('map');
    this.mapDimensions = map.getBoundingClientRect();
    this.mapWidth = this.mapDimensions.width;
    this.mapHeight = this.mapDimensions.height;
    this.scene = new THREE.Scene();
    this.scene.background = new THREE.Color( 0xf0f0f0 );

    //Camera:
    this.camera = new THREE.PerspectiveCamera(
      60,
      this.mapWidth/this.mapHeight,
      0.1,
      1000,
    );
    this.camera.position.z = 3;

    // renderer and canvas creation:
    this.renderer = new THREE.WebGLRenderer();
    this.renderer.setSize(this.mapWidth, this.mapHeight);
    map.appendChild(this.renderer.domElement);

    // EVENT LISTENERS:
    map.addEventListener('mouseover', this.highlightPoi, false);
    map.addEventListener('mouseover', this.mouseOverScene, false);
  },

  // HELPER FUNCTIONS:

  mouseOverScene (event) {
    event.preventDefault();
    let rect = event.target.getBoundingClientRect();
    let x = event.clientX - rect.left;
    let y = event.clientY - rect.top;

    this.mouse.x = ( x / this.mapWidth) * 2 - 1;
    this.mouse.y = - ( y / this.mapHeight ) * 2 + 1;

    this.rayCaster.setFromCamera(this.mouse, this.camera);
  },


  animate() {
    requestAnimationFrame(this.animate);
    this.render();
  },

  render() {

    // find intersections

    let highlighted = this.highlighted;
    let renderedRaycaster = this.rayCaster;
    renderedRaycaster.setFromCamera(this.mouse, this.camera);

    let intersectHighlighted = this.intersectHighlighted;
    intersectHighlighted = renderedRaycaster.intersectObjects(this.spheres);

    if (intersectHighlighted.length > 0) {
      console.log("I'm in if 1");
      if (highlighted !== intersectHighlighted[0].object) {
        if ( highlighted ) highlighted.material.color.setHex( highlighted.currentHex );
        console.log("I'm in if 3");

        highlighted = intersectHighlighted[0].object;
        highlighted.currentHex = highlighted.material.color.getHex();
        highlighted.material.emissive.setHex( 0xff0000 );
        console.log(intersectHighlighted.length);
      }
    } else if (intersectHighlighted !== this.spheres.object) {
      console.log("I'm in else");
      if ( highlighted ) highlighted.material.color.setHex( highlighted.currentHex );
      highlighted = null;
      console.log(highlighted);
      console.log(intersectHighlighted);
      console.log(intersectHighlighted.length);
    }

    this.renderer.render(this.scene, this.camera);
  },
},

EXPECTED RESULT: When hovering over the sphere with the mouse, it should change color to highlight and revert to its original color when not hovered over.

ACTUAL: It only highlights one sphere and does not return to the original color upon unhovering.

Answer №1

My approach to the issue:

After carefully analyzing the problem, I realized that the solution lied in reworking my code using linked lists logic. By switching the global variables to local ones, I unintentionally disrupted my code. Additionally, changing the mouseover event handler to mousemove allowed for continuous updating of mouse coordinates. Here's the revised code snippet:

init(){
    map.addEventListener('mousemove', this.mouseOverScene,false);
},

render() {


    // locate intersections

    this.rayCaster.setFromCamera(this.mouse, this.camera);

    this.intersectHighlighted = this.rayCaster.intersectObjects(this.spheres);

    if ( this.intersectHighlighted.length > 0) {
      if (this.highlighted !=  this.intersectHighlighted[0].object) {
        if ( this.highlighted ) this.highlighted.material.emissive.setHex( this.highlighted.currentHex );

        this.highlighted =  this.intersectHighlighted[0].object;
        this.highlighted.currentHex = this.highlighted.material.emissive.getHex();
        this.highlighted.material.emissive.setHex( 0xff0000 );
      }
    } else {
      if ( this.highlighted ) {
        this.highlighted.material.emissive.setHex( this.highlighted.currentHex );
      }
      this.highlighted = 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

Transforming text colors dynamically using Vue.js

Here is an Angular code snippet: <div [style.color]="'#' + prod.id.substring(0,6)"> <small>{{ prod.id }}</small> </div> Now I want to create a similar code using vue.js. ...

The Heroku app is having trouble communicating with the Mongo Atlas database, leading to frequent crashes

My deployed application on Heroku was working fine until I encountered an issue with the connection to my MongoDB Atlas database. Despite my attempts to resolve it, the application keeps crashing. The Heroku logs show the following: "2022-12-05T10:19: ...

Having trouble with DataTables functionality in Laravel blade views?

Blade template with a query: @extends('2a.layouts.master') <link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script s ...

The integration of HTML and CSS using ng-bind-html appears to be malfunctioning

<ion-item ng-bind-html="renderHtml(word[key])"> </ion-item> When referring to word[key], it represents: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> This is the CSS being u ...

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

How can I execute route-specific middleware in advance of param middleware in Express v4?

Let me share a unique situation in my routing setup where I need to trigger a middleware before the parameter middleware is executed: router.param('foo', function (req, res, next, param) { // Accessing the param value ... next() }) router ...

Determine the URL path of the linked page using jQuery's ajax method

Hey there! I'm working on a Rails application and I'm trying to figure out how to retrieve the path name for an ajax URL. When it comes to the current path, I've been using URL:window.location.pathname. But is there a way to obtain the path ...

The data type 'string' cannot be assigned to type [object]

Here's a scenario using an interface: interface Order { symbol: string side: string price: number quantity: number } In my code, I have a section where I am trying to access values within a table. However, it's giving me an error saying tha ...

What is the best way to display the UID of a Firestore sub-collection publicly while

I have a Firestore database structure set up as shown in image 1. I am looking to allow unauthenticated users of my web application to view the public profiles of plumbers, along with the reviews (image 2) they receive from completed jobs. My main query is ...

Tips for extracting value from a button inside a while loop in a modal

As I was working on my code, I encountered an issue with displaying pictures in a modal when a user clicks on a button. Here is the code snippet that I used to display the products and set up the session to store the selected picture for the modal. However ...

Utilizing Three.js to Create a PlaneGeometry that Completely Fills the

Excited to explore THREE.JS, I'm currently working on an Angular project to create a waving flag animation. Check out my progress so far: https://stackblitz.com/edit/angular-edgwof?file=src/app/app.component.ts My goal is to ensure that the plane fi ...

React application created with create-react-app that uses multiple environment files for varying configurations

I've been working on setting up various environment files for a React project (using create-react-app). I referred to the official documentation, but I encountered the following error: '.env.development' is not recognized as an internal or ...

Is there a way to extract the numerical value from a string within an ID of a div and transform the rest of the string into a variable?

Looking to extract the final id of a div and convert it to a variable. <div class="margin_bot" id="itemRows2"> <p id="rowNum1">...</p> <p id="rowNum2">...</p> <p id="rowNum3">...</p> <p id="rowNum4"> ...

Encountering a rollbackFailedOptional error during the NPM Install process

When attempting to use various command prompts like Windows Powershell, command prompt as an admin, and bash CMD, I encountered the same error message after trying to run npm install: npm install npm@latest -g The specific error message was: [...] / ro ...

establish connections within dynamic data table entries

As a newcomer to Javascript, I've been struggling with a particular question for some time now. The challenge at hand involves a dynamic jQuery table where I aim to hyperlink one row of the table data to a .php page in order to perform certain querie ...

What is the best way to retrieve data from a database and display it in a select dropdown list

I'm working on creating a Bingo game and I want to include a dropdown list that displays my previous records. How can I retrieve data from a database to populate this select dropdown list? Below is the relevant code snippet in PHP: <html> < ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

Displaying and hiding a large image using jQuery's mouseover event

I'm currently utilizing this jQuery script to toggle the visibility of an image with a fixed position: $(document).on('mouseover',".multiverseid", function (e) { var mid = $(this).attr("id"); $('#picture').attr('s ...

"Implement a function in Node.js/JavaScript that creates a new JSON object if the ID matches with the ID of another

const data = [ { system: { id: "4gSSbjCFEorYXqrgDIP2FA", type: "Entry", content: { type: { name: "Author" } }, }, DataDetails: { shortSlugOption: { "en-us": "some value", "za-op": "random value" }, ...