Issue with Three.js: real-time color updating for mesh not functioning

Attempting to create a simple program with an animation that switches the color of a traffic light from green to red and back every 2 seconds, but the color change is not working as expected.

I have tried debugging the code by printing the booleans that should trigger the color change, and everything seems correct. However, the color remains unchanged. The element I am trying to modify is called "bombilla" and the color change function is called "changeColor" which is being executed every two seconds using setInterval()


// JavaScript code for creating a simple animation

var scene;
var camera;
var renderer;
var cube;
var cylinder;

var red = 1;

// Create the scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0xf0f0f0);

// Create orthographic camera and add it to the scene
camera = new THREE.OrthographicCamera(window.innerWidth / -200, window.innerWidth / 200, window.innerHeight / 200, window.innerHeight / -200, 0.1, 1000);
scene.add(camera);

// Create a renderer for the scene
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

cube = new THREE.BoxBufferGeometry(1, 1, 1);
cylinder = new THREE.CylinderGeometry(0.1, 0.1, 5, 100);

// Define various mesh elements
var carga = new THREE.Mesh(cube, new THREE.MeshLambertMaterial({ color: 0xA6A6A6 }));
var cabina = new THREE.Mesh(cube, new THREE.MeshLambertMaterial({ color: 0xF2F2F2 }));
// More mesh definitions...

scene.add(carga);
scene.add(cabina);
// Add more mesh elements to the scene...

// Create directional light for the scene
var light = new THREE.DirectionalLight(0xffffff, 1.5);
light.position.set(2, 1, 5).normalize();
scene.add(light);

var init = function() {
    // Initialization function to set up the initial positions and scales of mesh elements
    // Omitted for brevity...
};

// Function to change the color of the bulb (traffic light)
var changeColor = function() {
    if (red == 1) {
        bombilla.material.color.set(0x0CAB00);
        red = 0;
    } else if (red == 0) {
        bombilla.material.color.set(0xFF0000);
        red = 1;
    }
}

var update = function() {
    // Call the changeColor function every 2 seconds
    setInterval(changeColor, 2000);
};

var render = function() {
    renderer.render(scene, camera);
};

var GameLoop = function() {
    // Main game loop function
    init();
    update();
    render();
};

GameLoop(); // Start the game loop

Answer №1

There are a couple of issues with your current code that need to be addressed.

The first issue is that the requestAnimationFrame() function is commented out, meaning that the scene is not being rendered continuously. This results in any animations or changes made to the scene being ineffective.

However, the more significant problem lies in using setInterval within the animation loop to determine when to change the material color. By calling setInterval on every frame update, the material color will start swapping after two seconds and continue changing with each frame update.

To resolve this, you should check if two seconds have elapsed since the last update before executing the changeColor function. This can be efficiently managed by utilizing THREE.Clock.

// Global scope
var clock = new THREE.Clock(); // Automatically starts the clock

// Update function
var update = function() {
  var time = clock.getElapsedTime(); // Elapsed time since the last reset
  if (time > 2) {
    changeColor();
    clock.start(); // Resets the clock
  }
};

Check out the JSFiddle for implementation details.

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's preventing me from adding additional meshes to my threejs scene?

Need some help with threejs as a beginner. I've been trying to add a simple mesh (torus with MeshBasicMaterial) to a scene, but it's not showing up. Any idea why? My goal is to add a sphere to the earth scene. There are no errors, but the object ...

Guide to attaching a mouse click event listener to a child element within a Polymer custom component

I'm currently facing an issue where I am attempting to attach a click listener to one of the buttons within a custom element during the "created" life cycle callback (even attempted using the "ready" callback with the same outcome). Unfortunately, I ...

Tips for effectively passing navigation as props in React Navigation with Expo

How can I correctly pass navigation as props to another component according to the documentation? The navigation prop is automatically provided to each screen component in your app. Additionally, To type check our screens, we need to annotate the naviga ...

Error: The variable "message" has not been defined. Please define it before displaying the welcome

While I was experimenting with my welcome message and attempting to convert it into an embed, I ended up rewriting the entire code to make it compatible. However, upon completion, I encountered the error message is not defined. var welcomePath = './ ...

How can I set up multiselect values in AngularJS ui-select?

Solution: Success! I managed to resolve the issue by implementing this solution and creating a customized build of the ui-select. Hopefully, this fix will be incorporated into the official master branch soon! Issue Is there a way to set up a select elem ...

Error in HTML Sorting

I've been experimenting with some code from this fiddle: http://jsfiddle.net/kutyel/5wkvzbgt/ but when I copy it into Notepad++ and run it, it only displays: <html> Id: {{result.id}} Product: {{result.name}} Price: {{result.price | currency} ...

Utilizing Redux in my ASP.NET MVC application with the help of RequireJS and TypeScript (Issue: Encountering a script error for "redux" dependency)

I'm currently working on integrating the Redux state library with my ASP.NET MVC application using TypeScript and RequireJS. For this simple application, I have set up a new ASP.NET MVC Project and stripped it down to only include the necessary node ...

Tips for eliminating the backslash introduced by JQuery

Switching back from framework 4.5 to 4.0 caused several issues that needed fixing. One significant change I noticed was that jQuery started escaping double quotes. Is there a way to stop this behavior? I attempted datatest = datatest.replace("\\ ...

Showing the information obtained from an API request once the user submits the form without the need to reload the page

I am currently working on a form that will take search query requests from users upon submission and then display the results by making an API call. My goal is to show these results without the page having to refresh, using AJAX. The backend connection to ...

JSON parsing in C#

I'm struggling to parse JSON in c# that is structured like the example below. The code snippet I have been using is somewhat functional, but it lacks stability. (I'm also looking for guidance on how to parse JSON in Javascript, which is another ...

Issue with rendering Angular templates

Having just embarked on my AngularJS journey, I'm currently facing an issue with this specific code snippet. The following is an excerpt from my JavaScript file named cribsController.js: angular .module('ngCribs') .controller('cribsCo ...

Transmit information from an HTML input field (not a form) to a Python CGI script through AJAX

I am currently facing a challenge where I need to send data programmatically without using form fields directly to a python CGI script. The issue lies in not knowing how to extract this data in Python. Normally, with a form, I could use "form = cgi.FieldSt ...

Can one utilize Javascript to write in plain text format?

Currently, using JavaScript I have a plain text containing data that is displayed within my form tags. Everything is functioning correctly, but now I need to update the values inside the code of my form tags in order for the changes to also be reflected in ...

What are some methods to maintain consistent height for each list item in an unordered list on small screens like mobile devices?

While vh works well for larger screen sizes such as laptops, it may not maintain the height of the li on smaller devices like mobiles. Is there a better approach than relying on media queries to achieve responsiveness across different screen sizes? ...

The Vue application is encountering an unexpected error in Chrome that is puzzling me as I search for a solution

Currently, I am delving deep into learning Vue.js and have decided to revisit the documentation from scratch and work through it in reverse order. Below is the content of my index.html file: <!DOCTYPE html> <html lang="en"> <hea ...

Pass for Achieving the Bokeh2 Effect

I'm attempting to transfer the Bokeh2 Depth of Field effect to an effect composer pass. Every time I try to run it, I encounter the following error: glDrawElements: Source and destination textures of the draw are the same. Below is the render functi ...

How can I load data from the server into CKEditor in React.js once the data is loaded?

Need to make changes in my code for editing an article item: const [contentEditor, setContentEditor] = useState(null); useEffect(() => { async function getLoadData(){ setitem(""); setContentEditor("" ...

What is the best way to create a slideshow using an IFrame?

Currently seeking a solution for an iframe slideshow that can smoothly transition between multiple HTML iframes. I have a total of 5 iframes that need to rotate automatically and continuously. Any suggestions on how to build a lively and dynamic iframe sl ...

Implementing an API call using Redux Saga within a React application

I have been diving into learning saga by following a tutorial on Medium and trying to implement it in StackBlitz. I encountered a path issue initially, managed to fix it after several attempts, but now a different problem has come up. Despite searching on ...

Managing Actions in React-Redux: Understanding the Dispatch Function

While I am delving into the world of React, I stumbled upon an example that looks like this: //index.js const store = createStore(reducer) render( <Provider store={store}> <AddTodo /> </Provider>, document.getElementById(' ...