Replace the transformation matrix of a three.js object/mesh entirely

Creating a new object in three.js

In order to create a three.js mesh object, follow these steps:

    var geometry = new THREE.BufferGeometry();

    var standardMaterial = new THREE.MeshStandardMaterial( {/* inputs */ } );

    var mesh = new THREE.Mesh( geometry, standardMaterial );

    // Next, add the mesh as an object to the 3D scene.

Setting the transformation matrix

If you wish to set the transformation matrix of an object, use the code snippet below:

            object = ... // Object is already created and passed around.

            const pkm = ... // Contains 16 numbers (equivalent to a 4x4 matrix).

            var matrix = new THREE.Matrix4();

            matrix.set(
                pkm.X00, pkm.X01, pkm.X02, pkm.X03,
                pkm.X10, pkm.X11, pkm.X12, pkm.X13,
                pkm.X20, pkm.X21, pkm.X22, pkm.X23,
                pkm.X30, pkm.X31, pkm.X32, pkm.X33,
            );

            object.applyMatrix4( matrix );
            object.updateMatrixWorld( true );

Issue with replacing the transformation matrix

The current method of setting the transformation matrix simply multiplies the new matrix with the existing matrix of the object. However, the requirement is to replace the existing matrix entirely with the new matrix.

What is the recommended best practice for completely replacing the existing matrix of a three.js object or mesh with a brand new one?

Attempts using AI chatbots

Various solutions recommended by AI tools like and were tested, but some of them failed, such as:

object.matrix = matrix;
object.matrixAutoUpdate = false;
object.updateMatrixWorld(true);
object.matrix.setFromMatrix4(matrix);
object.matrixWorldNeedsUpdate = true;
object.matrix.copy(matrix);
object.matrixWorldNeedsUpdate = true;
object.matrix.identity();
object.matrix.copy(newMatrix);  
object.updateMatrixWorld(true);
object.matrix.set(pkm.X00, pkm.X01, ... )
object.matrixAutoUpdate = false;
object.updateMatrixWorld(true);

Answer №1

Important Update

Following the advice shared by @Mr.Coder, it seems that the suggested approach should work smoothly:

... my experience has shown that when manually setting a matrix, it is necessary to disable matrixAutoUpdate and refrain from using updateMatrix or updateMatrixWorld on it ... This insight was taken from:

Previous Solution Details

It appears that the issue stemmed from the position values within the transformation matrix. These values need to be manually set after configuring the matrix.

It seems that the current functioning code snippet looks like this:

object = ... // Already initialized and being used.

const pkm = ... // Holds 16 numbers, representing a 4x4 matrix.

var matrix = new THREE.Matrix4(); // Initialization of a new matrix.

matrix.set(
    pkm.X00, pkm.X01, pkm.X02, pkm.X03,
    pkm.X10, pkm.X11, pkm.X12, pkm.X13,
    pkm.X20, pkm.X21, pkm.X22, pkm.X23,
    pkm.X30, pkm.X31, pkm.X32, pkm.X33,
);

object.applyMatrix4( matrix ); // Application of the new matrix to the object.
object.updateMatrixWorld( true );


// ** Interestingly, the position needs to be set individually.
// ** The reason behind this is not yet clear.
object.position.copy( new Vector3( pkm.X03, pkm.X13, pkm.X23 ) );

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 methods can be used to reveal the true value of data that has been encrypted?

Is it possible to retrieve the original value of data that has been hashed? Can the hashcode be reversed to reveal the real value of the data? String ida = new String(txtID.getText().toString()); int idb = ida.hashCode(); codeD.setText("result: " + ida) ...

Explore accessing a PHP array with multiple dimensions using Jquery Ajax

I have a PHP script that runs a SQL query on my MSSQL Server instance and returns a good result. Now, I'm attempting to manipulate the result using $.ajax in jQuery, but it seems that accessing fields in an object table via "Object.field_name" is not ...

Edit CSS attributes within Angular 2+ framework

When using jQuery, we have the ability to do the following: JQuery('.someStyle') .css({"background", "red"}) This allows us to directly change the CSS property in style. While working with Angular 2+, we can use [style.<property>] for ...

Ways to implement debounce in handling onChange events for input fields in React

I've been attempting to implement debounce functionality in my React app without relying on external libraries like lodash or third-party node modules. I've tried various solutions found online, but none have worked for me. Essentially, in the h ...

What is causing the recursion function to return "NaN" in this scenario?

I'm trying to calculate the total sum of absolute differences between consecutive elements in an array using a function called sumAbsArr, but it seems to be returning NaN. var arr = [1, 5, 2]; var n = 3; var cur = 0; console.log(sumAbsArr(arr, n, ...

Angular, a Self-sufficient Module of Cascading Style Sheets

I have developed a factory that generates HTML content. I want to showcase this generated HTML within a specific section of my application, without its CSS affecting the rest of the site, and vice versa. While using an iframe is one option, I believe there ...

Guide to decoding JSONP data sent from a remote server

Working on retrieving data using JSONP. After observing the returned data in Firebug, I can confirm that it is being returned correctly. However, I am facing a challenge in figuring out how to parse it. Is the data returning as a nested array? The callback ...

Ways to handle parsing of curly brackets JSON in Google Apps Script?

How can I use Google Apps Script to parse through the output of an API and convert it into a table in Google Sheets? I attempted the following code, but it only returns Null values. var response = UrlFetchApp.fetch(url, options); var text = response.getCo ...

ng-show directive in AngularJS is not functioning properly when utilized with CLI

After setting up my Angular app with ng new app, I attempted to hide certain elements conditionally using ng-show. Unfortunately, it doesn't seem to be working as expected. <span ng-show="false">Angular App</span> Regardless ...

Alerts are essential for the proper functioning of the AJAX function. Without them

As I incorporate a substantial amount of AJAX with XML Http Requests on my website, I encounter a peculiar issue with a few random AJAX calls. There seems to be an execution problem within my JavaScript code in the onreadystatechange function where certain ...

Is there a preferred method for looping through a NodeList and transferring its elements without the need to convert them into an Array?

Take a look at this jsFiddle that showcases the issue. It seems that while iterating over and making changes to the NodeList directly, the counter variable i skips every other node. In the provided fiddle example, there are two lists, #one and #two, and t ...

Discovering the source DOM element that initiated ng-change

I am currently working with angularJS and have multiple <select> elements on my webpage, each with its own ng-change function. Here is an example: <select id="hairColorComponent" ng-model="hairColor" ng-options="option.name for option in ...

What steps can I take to streamline this code and enhance its elegance in writing?

Working on some practice problems involving higher-order functions, I managed to solve this particular problem. However, the code I used feels somewhat messy and not as elegant as it could be. Is there a better way to combine map and reduce for a cleaner s ...

What could be the significance behind these sudden pop-ups of console error messages?

var sendTitle = function() { var title = $("input[name='movie-search-title']").val(); getMovie(title) getQuotes(title) } $("input[name='movie-search-title']").keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); ...

Unlock the full potential of `enableReinitialize: true` by utilizing the options `destroyOnUnmount: false` and `forceUnregisterOnUnmount: false` in a

I am currently working on a wizard form using redux-form/immutable for creating and updating a form. An issue I'm facing is that when moving from tab1 to tab2 in the wizard form, the state (user inputs) in tab1 gets lost. I have experimented with di ...

Simple method for implementing a fade effect on a React component with raw JavaScript techniques?

I am seeking a way to have my React component smoothly fade in upon being mounted. The component's outermost DIV starts with inline style display:none. Within the componentDidMount() method, I've written the following code: let el = document.que ...

Issue persists: Ajax functionality remains nonfunctional, prompting the need for

My goal is to use the post input, and upon hitting enter, I want to dynamically replace <div id="mainPagePosts"></div> with new data without causing a page refresh. However, even after submitting the post, the page still refreshes, although I d ...

Retrieve values from an array of objects using their corresponding keys

I have an array populated with various objects containing different key-value pairs. I need to extract specific values from the array and determine if a certain value is present or not. function groupByName (contract) { const { age } = contract; const g ...

Is the background element rather than its input being focused upon when clicking in the link tool's dialog within ContentTools?

I am utilizing ContentTools within a Bootstrap modal. The issue I am facing is that when I select text and click the hyperlink tool, the link dialog pops up but immediately focuses on an element in the background (such as the modal close button). This prev ...

Manage YouTube video played within html code

I am working on a page that contains a YouTube video embedded in HTML. I am trying to find a way to stop the video when it is closed using the YouTube API, but so far my attempts have been unsuccessful. I have included SWFObject and jQuery in the code, yet ...