Trouble altering material of object using keypress in three.js

I have been attempting to assign colors from an array to my object when a key is pressed, but I am only able to access the first element of the array. Is there another method that could be used for this purpose?

One approach I considered was using a random color function, however, my specific requirement does not involve randomly choosing colors.

 var onKeyDown = function(event) {

    if (event.keyCode == 67) { // when 'c' is pressed
                                 var index=0;    

                                object.traverse( function( child ) { if ( child instanceof THREE.Mesh ) {

                                        if (child.material.name == "Leather")  {
                                           var colors = [0xff0000, 0x00ff00, 0x0000ff]; // red, green and blue
                                            if(index == colors.length) index = 0;
                                            child.material.color.setHex(colors[index++]);
                                            child.material.needsUpdate=true;
                                            child.geometry.buffersNeedUpdate = true;
                                            child.geometry.uvsNeedUpdate = true;

                                        }
                                        }});

                            } };
                                document.addEventListener('keydown', onKeyDown, true);

Answer №1

The variable 'index' is currently located within the local scope of a function, which means it gets initialized (var index=0;) every time the C key is pushed.

To resolve this issue, simply move the variable outside of the function and your code will work as expected.

var index=0,
onKeyDown = function(event) {
    if (event.keyCode == 67) { // when 'c' is pressed
        object.traverse( function(child) { 
            if (child instanceof THREE.Mesh) {
                if (child.material.name == "Leather")  {
                    var colors = [0xff0000, 0x00ff00, 0x0000ff]; // red, green and blue
                    if(index == colors.length) index = 0;
                    child.material.color.setHex(colors[index++]);
                    child.material.needsUpdate=true;
                    child.geometry.buffersNeedUpdate = true;
                    child.geometry.uvsNeedUpdate = true;
                }
             }
        });
    }
};

document.addEventListener('keydown', onKeyDown, true);

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

The AngularJS factory does not hold on to its value

I have developed a basic factory to store a value from my authService: app.factory("subfactory", function() { var subValue = {}; return { set: set, get: get }; functi ...

Guide on capturing JSON objects when the server and client are both running on the same system

I created an HTML page with a form that triggers JavaScript when submitted using the following event handler: onClick = operation(this.form) The JavaScript code is: function operation(x) { //url:"C:\Users\jhamb\Desktop\assignmen ...

Ways to refine data using multiple criteria

I have a list of alarm data that I need to filter based on specific conditions. If there are multiple alarms of type "pull_Alarm" and "emergency_alarm" in the same location, I want to prioritize the "emergency_alarm". Here is my list: [ { ...

Get the file from the web browser

Hey there, greetings from my part of the world. I have some straightforward questions that I'm not sure have simple answers. Currently, I am working on a web application using the JSP/Servlet framework. In this app, users can download a flat text fil ...

"Encountering a mysterious internal server error 500 in Express JS without any apparent issues in

My express.js routes keep giving me an internal server error 500, and I have tried to console log the variables but nothing is showing up. Here are the express routes: submitStar() { this.app.post("/submitstar", async (req, res) => { ...

The onclick function in the Navbar div fails to work for inner elements

Within my navbar, there is a .dropbtn div that I want to trigger a dropdown function when clicked. However, only the text "TOTAL" seems to activate this function onclick. The <span> and <i> elements inside the .dropbtn do not respond to clicks ...

The element's position remains unchanged after the .click re-event in the function

Welcome to my first attempt at using jQuery! Please bear with me as I navigate through this learning process. Here's the challenge: I have a series of elements in my HTML. <div class="garden"> <div class="point left">&#9668;</d ...

Uncertainty about the integration of a JavaScript file into a PHP file

Having two PHP files where one is executed through a URL and makes AJAX calls to the second PHP file can present challenges. Sometimes, the AJAX results return HTML content with JavaScript events that do not work as expected. To solve this issue, I have in ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

how to handle form submission using JavaScript's return method

As a developer, I have created a single page that fetches data from a registration page. On this page, each data row has an "add" and "unfriend" button, with the latter initially disabled. When a user clicks the "add" button, a prompt box appears asking ...

Amchart 5: Tracking Cursor Movement on the X Axis

I am a beginner with amCharts5 and I am in need of assistance to retrieve the actual X value of the cursor on my chart (where the X axis represents dates). I have come across helpful examples for amCharts 4, but nothing seems to work for amCharts 5. Is thi ...

Receiving HTTP POST data using Classic ASP script

I'm currently working on a project and have come across an area where I am facing some challenges. Despite my best efforts, I haven't been able to find a solution using Google. In my ASP web application, I've added an HTML canvas that I nee ...

Having trouble with the `click()` function not working on a button while using Selenium in

Currently, I am running a selenium test on a remote server in headless mode using the chrome driver. However, when trying to click on a button with the following step, the button does not get clicked. Below is the test step attempting to click the element ...

Creating a ROT13 cipher in JavaScript

In my JS function, I need to handle a variable called i. My goal is to encode this variable using ROT13 before proceeding with the function. The challenge lies in decoding the variable and integrating it into the script. I came across a JavaScript implem ...

What steps can I take to make sure a particular node is successfully loaded and ready for use using JavaScript/jQuery?

When making a reservation at a hotel using the CJS Chrome extension, I am attempting to extract information about available rooms and rates both when the page loads and when the user changes dates. My current method involves injecting JavaScript into the p ...

Unexpectedly, Internet Explorer 11 is causing the "input" event to fire prematurely

While troubleshooting a JavaScript issue, I came across what seems to be a bug in Internet Explorer 11. I am reaching out here on StackOverflow for validation and to see if anyone else using IE11 can replicate this problem. The problem arises when the val ...

Typing text into an input field by tapping on a picture

Is there a way to create a feature where users can browse and insert images, which will pull the image URL (all image information is stored in a database) into an input field for submission? Similar to how WordPress allows you to browse, select an image, ...

Tips on adjusting a position that shifts with changes in window size

Working on a website for my grandpa, I'm planning to include a small biker character that runs across the screen. When hovered over, he stops and advises "wear a helmet." The animation works well, but there's an issue with the positioning when th ...

Switch the script: convert from jQuery to traditional JavaScript code

I've been trying to transition from using jQuery for a toggle script on my website to just using normal JavaScript in order to clean up the code. However, I'm having trouble converting the existing jQuery code into vanilla JavaScript. Here is th ...

Leveraging ajax data to enhance visual representation in graphs

Having trouble fetching data from a database to display it in a graph.js graph. I've attempted setting a timeout for the async callback from Ajax, but nothing seems to be working. Any suggestions on how to make this work would be greatly appreciated! ...