Utilizing raycasting for accentuating a line of 3D objects in a three.js

I'm currently working on using raycaster to detect a row of 3D cubes for highlighting and coloring upon mouse hover. I've been following the guidance provided in this post Change color of mesh using mouseover in three js. However, I've encountered an issue where only the cube directly under the mouse cursor is being highlighted instead of the entire row. Below you can find the pseudocode I have implemented:

var cubesList = new THREE.Group();

function createScene () {
    var cubeSize = 2;

    for ( var i = 0; i < noOfEntries; i++ ) {
        var entry = entries[ i ];
        var entryObjects = entry.objects;
        var entryCubesGroup = new THREE.Group();
        var noOfObjects = entry.objects.length;
        
        for ( var j = 0; j < noOfObjects; j++ ) {
            var object = entryObjects[ j ];
            var cube = createCube( cubeSize ); //THREE.Object3d group of 9 cubes
            entryCubesGroup.add( cube );
            
            if ( j === Math.round( noOfObjects / 4 ) - 1 && i === Math.round( noOfEntries / 4 ) - 1 ) {
                cameraTarget = cube;
            }
        }

        cubesList.add( entryCubesGroup );
    }

    scene.add( cubesList );

    camera.position.x = 15;
    camera.position.y = 15;
    camera.position.z = 15;
    camera.lookAt( new THREE.Vector3( cameraTarget.position.x, cameraTarget.position.y, cameraTarget.position.z ) );

    var light = new THREE.PointLight( 0xffffff, 1, 0 );
    light.position.set( 15, 15, 5 );
    light.castShadow = true;
    scene.add( light );
}

function animate () {
    renderer.render( scene, camera );
    update();
}

function onDocumentMouseMove ( event ) {
    event.preventDefault();
    mouse.x = ( event.clientX / renderer.domElement.width ) * 2 - 1;
    mouse.y = -( event.clientY / renderer.domElement.height ) * 2 + 1;
    animate();
}

function update() {
    var vector = new THREE.Vector3(mouse.x, mouse.y, 1);
    vector.unproject(camera);
    var ray = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
    
    var intersects = ray.intersectObjects(eventCubesList.children, true);

    if (intersects.length > 0) {
        if (intersects[0].object != INTERSECTED) {                       
            if (highlightedRow)
                unhighlightRow(highlightedRow);
            
            INTERSECTED = intersects[0].object;
            var timestamp = INTERSECTED.userData;
            var selectedRow = getSelectedRow(timestamp);
            highlightedRow = selectedRow;
            highlightRow(selectedRow);
        } else {
            if (INTERSECTED) {
                if (highlightedRow) {
                    var timestamp = INTERSECTED.userData;
                    var row = getSelectedRow(timestamp);
                    unhighlightRow(row);
                }
                highlightedRow = null;
            }
            INTERSECTED = null;
        }
    }
}

function unhighlightRow(cubes) {
    for (var i= 0; i < cubes.length; i++) {
        var cube = cubes[i];
        for (var j = 0; j < cube.children.length; j++) {
            var child = cube.children[j];
            child.material.color.setHex(cube.originalColor);
        }
    }
}

function highlightRow(cubes) {
    for (var i = 0; i < cubes.length; i++) {
        var cube = cubes[i];
        for (var j = 0; j < cube.children.length; j++) {
            var child = cube.children[j];                       
            child.material.color.setHex(0xffff00);
            break;
        }
    }
}

Is there any method available to highlight all the cubes in a particular row as yellow rather than just a single cube?

Answer №1

It is important to maintain a record of the location of each cube within the rows. Whenever a cube is selected, it is necessary to find out its corresponding row and highlight all other cubes in that row.

---sample code snippet---

SELECTED_CUBE = selectedItems[ index ].item;
row = findRowOfItem(SELECTED_CUBE)
for each item in row
   makeItemStandOut(item)

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

React Native - Implementing asynchronous array filtering using async/await

In my code, there is a filtering method implemented as follows: _filterItems(items) { return items.filter(async item => { let isTrue = await AsyncStorage.getItem('key'); return isTrue; }) } However, when calling the method this._ ...

`Can you explain how to specify the elements of an array within a form using AngularJS?`

Below is an array containing objects: //Data source code $scope.data = [ { name: 'Lname', items: [{ label: 'Lastname', type: 'text', model: 'lname', pattern: '/^[a-zA-Z]$/', ...

Creating a hierarchical list structure from a one-dimensional list using parent and child relationships in JavaScript

I am in the process of developing a web application that requires handling nested geographical data for display in a treeview and search functionality. The initial raw data structure resembles this: id:1, name:UK id:2: name: South-East, parentId: 1 id:3: ...

Change glb files to draco glb in the frontend

Can we encode and transform glb files into draco glb format using only frontend technologies (client side)? ...

Using javascript to display a vertical scroll bar within a dropdown menu

My challenge is to create a drop-down list that displays the first four items with a vertical scrollbar when the user clicks on it. The remaining items should be visible as the user scrolls through the list. You can find a sample fiddle here: http://jsfid ...

What is the best way to split two arrays of integers?

If you find yourself in a base 10 situation. You have the desire to divide int[] a = new int[] {9, 9}; by int[] b = new int[] {1, 0, 1}; Each element in both arrays consists of just one digit. When written out on paper, it appears as 99/101, resulting ...

Angular applications with separate, autonomous routers

Imagine having a massive enterprise application divided into multiple independent submodules (not to be confused with angular modules). I prefer not to overwhelm the routing in a single location and wish for these autonomous modules (non-angular modules) ...

Tips for concealing a button component on a specific route using react-router

Recently delving into the world of javascript and react, I've encountered a puzzling issue. Despite numerous Google searches, I've been unable to find a solution. The problem is that I'm attempting to hide a button component on one specific ...

Incorporate a 'back' button in the tab content of vue-form-wizard

Currently, I'm working on implementing a vue form wizard from the repository: https://github.com/BinarCode/vue-form-wizard My challenge is to include a button in the second tab-content itself instead of having it placed in the footer. I attempted th ...

RouterLinkActive is functional within ngFor

Preferably seeking a JavaScript solution, with Angular2 as the top choice I am currently attempting to generate my navigation bar dynamically based on an API call. The main issue I'm facing is ensuring that the parent li has an active class when ano ...

Tips on retrieving inner component data from an array in a Laravel Blade file format

issue with retrieving array data in Laravel blade template @foreach($connbid as $conaccept) {{$conaccept->contributer_id}}<br> @foreach($conaccept['accept'] as $acceptpost) {{ $acc ...

Ways to trigger an alert once a div is fully loaded with content

I have a webpage with a search feature. When the user clicks the search button, the results are fetched via ajax from the database and displayed in a div. After the results are displayed, I want to perform an action as soon as the total count of records i ...

Avoid unnecessary re-renders in ReactJS Material UI tabs when pressing the "Enter

I've created a user interface with tabs using material-ui in reactJS. The issue I'm facing is that every time a tab is selected, the content under that tab reloads, causing performance problems because there's an iFrame displayed in one of t ...

Highlight the list-group item when it is clicked using React Bootstrap

I'm currently working on a project that involves two panels, each with a list group. This project is built using Bootstrap. Problem: When I click on the first list-group-item in panel 1, it changes to have the style "success". However, when I then c ...

Exploring the Differences in CSS Styling between Web and Mobile Platforms

Recently, I launched my new website and encountered a peculiar issue. Upon clicking on Pickup Date & Time, a bootstrap datepicker pops up like it should. However, the problem arises when viewing the website on mobile devices - the datepicker appears offsc ...

Is there a way to selectively transfer attributes and behaviors from an interface to a fresh object in typescript?

Is there a way in javascript to selectively copy properties from one object to another? I am familiar with using Object.assign() for this purpose. Specifically, I am looking to extract only the properties defined within the following interface: export in ...

Using a jQuery gallery can cause links to become unresponsive and unclickable

While creating a responsive webpage with the Zurb Foundation framework, I encountered an issue when trying to incorporate nanoGallery which also uses jQuery. After adding the gallery scripts, the top menu generated by the Foundation script became unclickab ...

Trouble arises when attempting to retrieve the ID of the parent <ul> element using .parents() and .closest() in jQuery

Currently, I have 2 distinct <ul> containers with separate id's. Each of these contains a list of <li> elements. The first container is identified as <ul id="coaches-list">, while the second is labeled as <ul id="players-list"> ...

Tips on successfully submitting a complicated form with Jquery's AJAX functionality

I'm attempting to use Jquery's ajax to submit a form that contains textboxes, checkboxes, and a dropdown with multiple selection options. Someone advised me to collect the values of selected checkboxes using $("input:checkbox[name=type]:checked ...

Generating views for individual models in a backbone collection

Currently, I am developing a small backbone.js application that simulates a library where CRUD operations can be performed. The core components of this application are the book model and the library collection (which stores books). var Book = Backbone.Mod ...