Utilizing Raycaster for modifying the Box's face color upon clicking

I've been experimenting with the raycaster in order to select faces of cubes that are created, and then change the color of the clicked face. So far, I've managed to make it work for selecting entire objects, but not individual faces of those objects.

Can someone please clarify the distinction between intersectObject() and intersectObjects()? I suspect this difference might be causing the issue.

Below is the code snippet attempting to select a cube face, which compiles but doesn't respond when clicking on a face:

function onDocumentMouseDown( event ){ 
    event.preventDefault();

    mouse.x = (event.clientX / renderer.domElement.width ) * 2 - 1;
    mouse.y = - (event.clientY / renderer.domElement.height ) * 2 + 1;

    raycaster.setFromCamera( mouse, camera );

    var intersects = raycaster.intersectObject( mesh );

    for (var i = 0; i < intersects.length; i++){
        intersects[ i ].face.color.setHex( 0xDDC2A3 );
        mesh.geometry.colorsNeedUpdating = true;
    }
    renderer.render(scene, camera);
   }

}

Here's one of the cubes in my scene:

var cubeGeometry2 = new THREE.BoxGeometry(5, 5, 5);
var cubeMaterial2 = new THREE.MeshLambertMaterial({color:0xffff00});
var cube2 = new THREE.Mesh(cubeGeometry2, cubeMaterial2);
//Cube position to sit on top of the plane, allow to cast shadows and add
cube2.position.x = -5;
cube2.position.y = -5;
cube2.position.z = -5;
scene.add(cube2);

Answer №1

Could someone please clarify the distinction between intersectObject() and intersectObjects()? I believe this may be relevant to the current issue at hand.

As stated in the documentation for THREE.Raycaster, intersectObject() requires a single object as input, while intersectObjects() requires an array of objects. However, this is not causing the problem you are experiencing.

The issue lies in how your material is configured. If you want each face to have its own color, you must set THREE.Material.vertexColors to THREE.FaceColor. It's important to note that this method only works with THREE.Geometry.

Check out this demo: https://jsfiddle.net/sv05rwny/

three.js R101

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

What is the specific jQuery event triggered when utilizing the append function on a textarea element?

I am currently setting up a system to detect any modifications in a textarea: <textarea id="log-box__data"></textarea> Modifications are made to the textarea exclusively using jQuery's append method: $(document).on('click', &a ...

Does creating a form render the "action" attribute insignificant in an AJAX environment?

When submitting forms exclusively through AJAX, is there any advantage to setting the action attribute at all? I have yet to come across any AJAX-form guides suggesting that it can be left out, but I fail to see the purpose of including it, so I wanted t ...

How to iterate over an array and assign values to distinct labels using AngularJS

Challenge My goal is to present the user with information about their upcoming 4 events. I have used splice on an array to extract the first 4 objects. Now, I need to iterate through these objects and display the relevant data. Each label is unique and w ...

Encountering a challenge in Angular 8: Unable to locate a supporting object matching '[object Object]'

I am having an issue trying to retrieve the Spotify API from the current user's playlists. While I can see it in my console, when I attempt to insert it into HTML, I encounter the following error: ERROR Error: Cannot find a differ supporting object ...

I need to input text into a specific element on the page, however there are four elements on the page that have identical properties

I am facing a dilemma where I need to input text into an element on the page. However, there are four elements with identical properties, making it challenging to find a unique locator. Does anyone have experience using Protractor for AngularJS web pages a ...

Is there a way to transform individual data into a collective group dataset?

Here is the input data provided: data = [ { name: "John Cena", groupName: "WWE" }, { name: "Nandini", groupName: null }, { name: "Rock", groupName: "WWE" }, { name: "Vinay", groupName: null }, { name: "Rey Mesterio", groupName: "WWE" ...

Removing all HTML elements within the div container

My HTML code includes the following: <div class="row" id="conditional-one"> <div class="large-12 columns"> <h3><?php echo $arrayStage_rule_one_title?></h3> <p> <?php echo $arrayS ...

Exploring the possibilities of infinite scroll in JavaScript using the Backbone framework

I've been grappling with this problem for three days straight. I've been attempting to incorporate scrolling into my backbone project using the https://github.com/paulirish/infinite-scroll plugin. Despite my best efforts to find a solution throu ...

The Limits of JavaScript Tables

Currently facing an issue with a webpage under development. To provide some context, here is the basic layout of the problematic section: The page features a form where users can select from four checkboxes and a dropdown menu. Once at least one checkbox ...

Issues with click events in the navigation menu

How can I make my menu close when clicking on other parts of my website, instead of opening? I know that I should use a click event for this, but when I implemented a click event, my menu encountered 2 unwanted problems: 1- Whenever I clicked on a menu i ...

Analyzing critical code paths for optimal performance

There is a function that accepts two arguments and an optional third argument. The function should return true if the first argument is greater than the second, false if not, unless the third argument is true, in which case it should return true if the fir ...

Invert the motion within a photo carousel

Is there anyone who can assist me with creating a unique photo slider using HTML, CSS, and JS? Currently, it includes various elements such as navigation arrows, dots, and an autoplay function. The timer is reset whenever the arrows or dots are clicked. Ev ...

The Swiper slider is unable to display several views at once in the slider layout

I recently started using the amazing swiper slider plugin available here My goal is to replicate the demo-no-210 from that repository. Here is the code snippet I am working with: index.html <!DOCTYPE html> <html> <head> <meta ...

Issues with the functionality of the accordion menu

I have implemented an accordion menu on my website. However, I am facing an issue where the 2nd menu always slides up when it gets loaded instead of sliding up after clicking on it. I want the behavior to change so that the sub menus elaborate only upon cl ...

Working with JSON data and extracting specific information within the grades

Here is a JSON data structure that contains information about a student named Alice and her grades in various courses: { "student": [{ "cert_id": "59826ffeaa6-b986fc04d9de", "batch_id": "b3d68a-402a-b205-6888934d9", "name": "Alice", "pro ...

the 'class' keyword cannot be utilized in ECMA6

I attempted to execute a class in ECMA2015 but encountered the following error: class Task { constructor(name) { this.name=name; this.completed = false; }; } I received the error below: class Task { ^^^^^ SyntaxError: Unexpected reserved word} Not ...

What is the best way to dynamically disable choices in mat-select depending on the option chosen?

I was recently working on a project that involved using mat-select elements. In this project, I encountered a specific requirement where I needed to achieve the following two tasks: When the 'all' option is selected in either of the mat-select e ...

Strategies for transferring all selected checkbox IDs to REST endpoint

I'm currently diving into web development and have set up a few checkboxes on my page. Right now, I have four checkboxes available. My goal is to send the IDs of the checkboxes that the user has checked to my "REST Service". Below is the code that I&a ...

The integration between Mongoose and GraphQL does not support populating models

It seems like I have encountered a unique issue that none of the existing solutions have been able to resolve. I am running a backend server with Apollo Server + Mongoose on localhost. However, I am facing difficulties in populating or creating the collect ...

Notify when a variable matches the value of a div

I am attempting to display an alert message when my JavaScript var is equal to the value of a div. Here is the code I'm using: function checkMyDiv() { var elementCssClass = document.getElementById("Target"); if (elementCssClass == "hello") ...