Unable to update cube textures at runtime using Three.js r59

I managed to create a cube using the canvas renderer with r59 of Three.js, and it has different textures on different sides, which renders fine. I can also animate this cube's position and rotation without any issues.

Now, here's what I'm trying to achieve: A) The cube should initially have an image texture on its front side. B) I need to move the cube out of the camera's view. C) Change the image texture on the cube. D) Move the cube back to its original position to make it visible again.

Steps A, B, and D are working as expected. However, I'm encountering a problem when I try to implement step C. The relevant code parts are highlighted below...

<body>
    <script src="build/three.min.js"></script>
    <script src="js/libs/tween.min.js"></script>
    <script>
        // all the necessary code and initialization
        // code snippets to create cube and textures
        // code snippets for animating the cube
        // function to change texture
    </script>
</body>

Within my project, I am performing various tweening operations (moving and rotating multiple objects) and calling the texture change function from there...

When I remove the line...

            cubeMesh.material = MatCollection[currentMat];

from the function, everything works perfectly. The cube moves in and out of view but always displays the same texture.

What adjustments should I make to fix this issue?

I appreciate your insights and suggestions.

Oliver

Answer №1

Task completed.

Instead of preloading the Material into an array of materials, I opted to create an array of individual textures named MyTextures. Then, I assigned a newly created material (using textures from the MyTextures array) to each side of the cube mesh.

  ...
        var MyTextures = [];
  ... proceeding to the init() function:
            neheTextureSMALL = new THREE.ImageUtils.loadTexture("test3.jpg");
            MyTextures.push( neheTextureSMALL );

            for (var myy = 0; myy<imgNameArray.length;myy++) {
                neheTexture = new THREE.ImageUtils.loadTexture(imgNameArray[myy]);
                MyTextures.push( neheTexture );
            }

  ... moving on to the changetexture() function:

            cubeMesh.material.materials[0] = new THREE.MeshBasicMaterial({map: MyTextures[currentMat+1], side: THREE.DoubleSide });
            cubeMesh.material.materials[1] = new THREE.MeshBasicMaterial({map: MyTextures[0], side: THREE.DoubleSide });
            cubeMesh.material.materials[2] = new THREE.MeshBasicMaterial({map: MyTextures[0], side: THREE.DoubleSide });
            cubeMesh.material.materials[3] = new THREE.MeshBasicMaterial({map: MyTextures[0], side: THREE.DoubleSide });
            cubeMesh.material.materials[4] = new THREE.MeshBasicMaterial({map: MyTextures[currentMat+1], side: THREE.DoubleSide });
            cubeMesh.material.materials[5] = new THREE.MeshBasicMaterial({map: MyTextures[currentMat+1], side: THREE.DoubleSide });

Overall, the solution functions adequately. However, there are visual discrepancies (such as the image appearing fragmented into triangles) that need attention. :-(

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

Trialing: Uncovering stylish emotional elements using Jest/Enzyme

When I made the switch from glamorous to emotion for my project, I realized there was one important aspect missing: testing. With glamorous, I used to locate elements using selectors like this: $component.find('StyledComponent'); $component.fi ...

Display corresponding div elements upon clicking an HTML select option

Is there a way to make a div visible when a corresponding select option is clicked, while hiding others? My JavaScript skills are lacking in this area. CSS #aaa, #bbb, #ccc { display:none; } The HTML (I'm using the same id name for option and d ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

What is the best way to execute my mocha fixtures with TypeScript?

I am seeking a cleaner way to close my server connection after each test using ExpressJS, TypeScript, and Mocha. While I know I can manually add the server closing code in each test file like this: this.afterAll(function () { server.close(); ...

Step-by-step guide on dynamically fetching additional images from a directory using php, jquery, and ajax

I have a scenario where I have multiple folders, each containing up to 20 images. On my HTML page, I want to display the first 5 images and provide a "click to view more" option to show the remaining 15 images when clicked. Currently, the issue I am facin ...

Why does the Google Tag Manager noscript tag show up as a string when using react-gtm-module?

Implementing Google Tag Manager Tags in a React/Next.js app hosted on Netlify, I used the react-gtm-module. While the gtm script tag in the head section works perfectly, the noscript tag in the body is displaying an iframe as a string: <body> < ...

Sending an Ajax request following validation with jQuery

After successfully validating a form, I attempt to make an ajax request. Strangely, if I remove the , after url: 'loginprivate.php', the PHP code functions properly but the validation does not. On the other hand, if I add the ,, the validation wo ...

Restrict the maximum and minimum time that can be entered in an HTML input

I've implemented a basic code feature that allows users to input minutes and seconds on my React website. <div> <span> <input defaultValue="0" maxlength="2"/> </span> <span>m</span> <spa ...

JavaScript's click() function cannot be used on text areas

Currently, I am in the process of creating a script for automating comments. During step one, I encountered an issue where the code is expected to simulate a click on this text area within a red box, but unfortunately nothing happened. Initially, I attem ...

Efficiently removing a duplicated component in Vue: A step-by-step guide

I am trying to find a way to target and remove a component that I duplicated using the v-for directive in my multiple stopwatch application. Currently, I can only delete the last duplicated component, but I want the ability to remove any targeted component ...

NodeJS: Speed up your workflow by compressing video files

In my quest to enhance the performance of my application, I am seeking ways to compress images and videos to their smallest possible size without sacrificing quality. This process is known as lossless compression. While the imagemin package has proven eff ...

Why are JS & jQuery's inArray() and indexOf() functions not functioning correctly when indexes are strings?

Here is an example of an array: var arr = []; arr['A string'] = '123'; arr['Another string'] = '456'; I am attempting to find the index of either '123' or '456'. Both methods below are returnin ...

Tips for ensuring that a THREE.Group is always displayed in front of other objects

I am attempting to display a set of transform controls in such a way that they are constantly visible to the user. However, when I disable DepthWrite or apply the AlwaysDepth function to the transform controls, I achieve the desired result but encounter an ...

Maintain checkbox state through page reloads using ajax

Currently, I am troubleshooting a script that is intended to keep checkbox values checked even after the page is reloaded or refreshed. The code snippet below was implemented for this purpose, but unfortunately, it doesn't seem to be functioning corre ...

Locate a jquery element that is within a parent element containing specific text

This is the format I currently have: <td width="270px"> <img class="bullet" border="0" valign="top" src="gray-bullet.gif"> this is the text </td> Can someone provide me with a query to specifically target the img element with the class ...

Tips on transforming JSON data into a hierarchical/tree structure with javascript/angularJS

[ {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"1","zid":"1","statename":"Karnataka"}, {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"2","zid":"1","s ...

Tips for accessing <Field> values in redux-form version 7.0.0

class CustomForm extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { const { Add, noteList } = this.props; Add('this is title value' , 'this is ...

Creating a Dynamic Bar in Your Shiny Application: A Step-by-Step Guide

Currently, I am developing a unique crowd funding shiny app to monitor donation amounts. Is there a method available that allows for the creation of a reactive bar in Shiny? Alternatively, is it feasible to achieve this using html, css, and javascript? He ...

Issue with slideout menu hyperlinks malfunctioning

Currently developing a site at , everything seemed ready for deployment until testing in 320x480 mode on mobile revealed that the links on the slideout menu were not working on any mobile device I tried, regardless of resolution or page. I've tried u ...

Simply drag and drop the image from your browser window into the file input

Is there a way to drag an image from a browser window into a file input that I developed? Looking for assistance in creating an event that allows me to get the image when dragging it to an input. While I have successfully created an event to obtain the i ...