Modifying the color of a cube in three.js

My goal is to modify the color of two cubes based on a certain variable. I have created both cubes and intend to adjust their color according to how close or far they are from each other.

The cubes were generated using the following code:

geometry = new THREE.CubeGeometry( 50, 50, 50 );
material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );
cube = new THREE.Mesh( geometry, material );
scene.add( cube );

I attempted this approach:

if(distance > 20)
{
cube.material.color = 0xffffff;
}

Unfortunately, this method did not produce the desired outcome. I searched through various examples but couldn't find a suitable solution.

Answer №1

The correct way to define the color value is not being provided.

cube.material.color.setHex( 0xffffff );

Answer №2

cube.material.color

You can retrieve the THREE.Color object by using the line above.

To learn more about the methods available for setting the color, check out the Color documentation.

Answer №3

To easily change the color of an object during runtime, a suggestion is to attach a function directly to the object itself.
Taking inspiration from your existing code snippet

const geometry = new THREE.CubeGeometry( 50, 50, 50 );
const material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );
const cube = new THREE.Mesh( geometry, material );

// Define and attach the color-changing function to the object
cube.setColor = function(color) {
     cube.material.color.set(color);
}

cube.setColor(0xFFFFFF); // Change color using hex value or
cube.setColor("blue");   // Set material color by using color name

scene.add(cube);

Answer №4

When working with materials, you have the option to use a hexadecimal color value For example:

meshMaterial = new THREE.MeshBasicMaterial({color:0xfffff})
In this code snippet, the hexadecimal value (0xffffff) represents the color white

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

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

Error in Express Post Request: Headers cannot be modified after being sent to the client

I am a beginner in Node.js and I am facing some challenges while working on an app for learning purposes. I encountered the following issue: Error: Can't render headers after they are sent to the client. I am unsure of how to resolve it. C:\Us ...

ng-repeat to prevent duplicate items from displaying

I intentionally have duplicates in my array of items and I am looking for a way to hide just one of them when clicked within my ng-repeat. Is there a way to hide only one of the duplicated items on click? I feel like I might be overlooking something, as ...

Creating a reusable function for making HTTP requests in Angular

I have a scenario in my controller.js where I need to make an HTTP GET request when the page loads and when the user pulls to refresh. Currently, I find myself duplicating the $http code. Is there a way to refactor this for reusability? I'm struggling ...

Encountering an error message related to Bootstrap carousel: "Unable to read property 'offsetWidth' of undefined"

Encountering a frustrating error message: "Cannot read property 'offsetWidth' of undefined" when using Bootstrap carousel. Let me share my code with you: <div id="myCarousel" class="carousel slide" > <ul class=& ...

Display streaming data continuously within an HTML page using Angular 16

Currently, I am actively developing a stream API that receives data with a 'Content-Type' of 'text/event-stream'. Below is a snippet from my stream.service.ts: connectToSse(): Observable<any> { return new Observable((observer ...

Calculate the sum of the column values and disable the option to insert new rows in the UI grid

I am currently working on a ui-grid that has a column C which displays percentage values. There is a button labeled "add rows" that allows users to add new rows to the grid. However, the catch is that users can only add new rows until the total percentage ...

How can I prevent the content from being pushed when the sidebar is opened in JavaScript and CSS? I want to make it independent

I'm struggling with making the sidebar independent of the main content when it's opened. I've included the CSS and JavaScript code below. Can someone provide assistance with this? function ExpandDrawer() { const drawerContent = docu ...

What are the steps to transform a blob into an xlsx or csv file?

An interesting feature of the application is the ability to download files in various formats such as xlsx, csv, and dat. To implement this, I have utilized a library called fileSaver.js. While everything works smoothly for the dat/csv format, there seems ...

Autocomplete is failing to provide any results

I am experiencing an issue with the autocomplete script as it is not displaying any names under the input field. Below is the code snippet from my index file: <head> <html lang="en"> <meta charset="utf-8"> <meta na ...

Creating orthographic units with Three.js

Looking for clarification on the units used in Three.js Matrix4.makeOrthographic( left, right, bottom, top, near, far ). Can anyone provide some insight? ...

What is the best way to add a value to a textbox?

Hey there, I have a question about inserting a jQuery value into my HTML code. I need some assistance with my HTML and jQuery code. Any help would be greatly appreciated! < script > $(document).ready(function() { $("#oroom").blur(functi ...

What is the best way to access the current element in a loop function?

I'm facing an issue with a nested each function and I need help on how to refer to the current item when the if statement is triggered: // checking for empty array if(sameValArr.length === 0) { $(this).hide(); // hiding the current video thumbnail ...

Checking for queryParam changes in Angular before ngOnDestroy is invoked

I am looking to conditionally run some code in the ngOnDestroy function depending on changes in the current route. Specifically, when the route changes from /foo to /login?logout=true, and this change is initiated outside of the Foo component. In the ngO ...

What is the process for retrieving the component along with the data?

As I work on compiling a list of div elements that require content from my firebase cloud storage, I find myself unsure about how to effectively run the code that retrieves data from firebase and returns it in the form of MyNotes. Consider the following: ...

Extracting specific attributes from an array to showcase on a single div

example: { "data": [ { "name": "banana", "color": "yellow" }, { "name": "kiwi", "color": "brown" }, { "name": "blueberry", "color": "blue" } ] } Instead of div, I want to use a span for each ...

Obtaining a byte array using the file input method

var profileImage = fileInputInByteArray; $.ajax({ url: 'abc.com/', type: 'POST', dataType: 'json', data: { // Other data ProfileImage: profileimage // Other data }, success: { } }) // Code in Web ...

After my jQuery functions are executed, my CSS rules are loaded

Struggling with the communication between CSS and jQuery, I find myself torn. In CSS, my rules are often very specific, like this: div#container > div#contentLeft { //Code here } However, when I add jQuery to spice up my site, the CSS rules seem to ...

How to attach an event listener to an input element using Angular

I am looking to add a listener to an input element that will be triggered every time the user changes the input values. The goal is to display the current values chosen by the user. Example HTML template: <div id="idDoseLabel1" class="da ...

Firebase: Saving data to a nonexistent object

I am currently facing a challenge in saving the result of a serviceId to a services object within a parent entity named provider1, especially since the services object has not been initialized yet. The structure of my Firebase data is as follows: "provid ...