The function Geometry.center() has not been used

Within my code, I am working with a BufferGeometry that undergoes changes in vertices and colors periodically. To manage this, I create a new buffergeometry if more space is required for vertices; otherwise, I reuse the existing one by adjusting its drawRange property.

However, an issue arises when I update the BufferGeometry with new vertices without triggering the center() function as expected. Although I apply center(), the geometry doesn't get centered correctly, leading to flickering between centered and non-centered positions. The problem seems to lie in the translate() performed during the center() function but somehow getting altered afterward. How can I resolve this inconsistency? Note that mesh.position remains constant throughout.

if(this.mesh != undefined && this.prev_len > vertices.length) {
        for (var i = 0; i < vertices.length; i++) {
            this.v.setXYZ(i, vertices[i][0], vertices[i][1], vertices[i][2]);
            this.c.setXYZW(i, colors[i][0], colors[i][1], colors[i][2], 1);
        }
        this.geometry.setDrawRange(0, vertices.length); 
        this.geometry.attributes.position.needsUpdate = true;
        this.geometry.attributes.color.needsUpdate = true;
        this.geometry.computeVertexNormals();

        // The issue seems to be related to center() not being applied properly.
        // Despite debugging three.js, it appears that the translate() method within the center() function is executed but then modified afterwards.
        this.mesh.geometry.center();

    } else {
        this.v = new THREE.BufferAttribute(new Float32Array(vertices.length * 3), 3);
        this.c = new THREE.BufferAttribute(new Float32Array(colors.length * 3), 3);
        for (var i = 0; i < vertices.length; i++) {
            this.v.setXYZ(i, vertices[i][0], vertices[i][1], vertices[i][2]);
            this.c.setXYZW(i, colors[i][0], colors[i][1], colors[i][2], 1);
        }
        this.geometry = new THREE.BufferGeometry();
        this.geometry.dynamic = true;
        this.geometry.addAttribute('position', this.v);
        this.geometry.addAttribute('color', this.c);
        this.geometry.attributes.position.dynamic = true;
        this.geometry.attributes.color.dynamic = true;
        this.geometry.computeVertexNormals();
        this.prev_len = vertices.length;

        if(this.mesh == undefined) {
            this.mesh = new THREE.Mesh(this.geometry, this.material);
            this.mesh.position.set(
                                   this.from_x,
                                   this.from_y,
                                   this.from_z
            );
            scene.add(this.mesh);
            this.geometry.center();

        } else {
            // When assigning the new geometry, it gets centered properly.
            this.mesh.geometry = this.geometry; 
            this.geometry.center();
        }

    }

Answer №1

After making changes to "this.geometry", you then use the method "center()" on "this.mesh.geometry". It could be possible that there is a broken connection between your BufferGeometry and the additional properties of the object "this".

Answer №2

After some investigation, it appears that the issue arises when center() is not properly applied to a geometry that has been updated with new positions. This can lead to a misleading offset due to changes in the position attribute.

To address this problem, I found a solution that involves saving the offset returned by geometry.center() and applying it to updated geometries.

this.offset = this.geometry.center();

Then, when updating the position, manually apply the offset like so:

this.geometry.translate(this.offset.x, this.offset.y, this.offset.z);

While I'm not certain if this is the most orthodox approach or merely a workaround, it has proven effective for my purposes.

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

Tips for preserving the content of a text field within the text field area

I have an HTML table with 3 fields, one of which is editable. The data for two columns is obtained as JSON - the fields are itemName and itemCode. The third column, Quantity, is manually created with a default value of 0. There is also a dropdown called ...

Dealing with errors when attempting to parse invalid input using JSON.parse()

While working on a solution to manage cookies in JS, I encountered an issue. The cookies I am dealing with can have content in JSON format, like so: var cookieContents = '{"type":"cookie","isLie":true}'; ... or they could simply be plain string ...

Creating formGroups dynamically for each object in an array and then updating the values with the object data

What I am aiming to accomplish: My goal is to dynamically generate a new formGroup for each recipe received from the backend (stored in this.selectedRecipe.ingredients) and then update the value of each formControl within the newly created formGroup with t ...

Apply a jQuery class to six randomly selected elements that share the same class attribute

I have a total of 12 elements that all have the "block" class, and I am looking to randomly assign the "active" class to exactly 6 out of the 12 elements. My initial thought was to use a for loop to achieve this task, but I'm unsure about how to go a ...

The BufferGeometry displaying in black when using PhongMaterial

I'm facing an issue while trying to render a buffer geometry object using a phong material as it appears black. Previously, when I used a basic material, the rendering was correct. To troubleshoot the lighting, I rendered a cube with phong material wh ...

Mastering the Proper Use of Bootstrap-Tagsinput in Angular2

I have been trying to incorporate the bootstrap-tagsinput library into my Angular2 project. I successfully installed the library using the package.json file: "dependencies": { ... "bootstrap-tagsinput": "^0.7.1", ... } After installation, ...

How to utilize JavaScript to convert a string into a function name

In this specific scenario, I am required to trigger a function based on the data attributes associated with an HTML element. function func1(arg1){ alert("func1"); } function func2(arg2){ alert("func2"); } jQuery(document).on('click', & ...

Trigger a bootstrap modal using JavaScript within a PHP environment

Upon encountering a failed login attempt, I attempted to open a Bootstrap modal using the code below: if (mysqli_num_rows($query) != 0) { // Login successful } else { // Login failed echo '<script type="text/javascript"> $("#LoginF ...

Using $emit to send parameters based on the route in Vue.js is essential for conditional communication

Is there a way to create a conditional statement based on the user's route? refreshData (){ var params = {}; for (var key in this.filters) { if (this.filters.hasOwnProperty(key)) { if ( this.filters[key] ...

How can JavaScript Regular Expressions be used for Form Validation?

For my registration form, I am including fields such as userid, name, email, password, confirm password, and affiliation. Using regular expressions in JavaScript, I am validating these fields. I am attempting to display any validation errors within the for ...

I'm feeling a bit lost with this API call. Trying to figure out how to calculate the time difference between the

Currently, I am working on a project for one of my courses that requires making multiple API calls consecutively. Although I have successfully made the first call and set up the second one, I find myself puzzled by the specifics of what the API is requesti ...

How do I show a personalized cookie banner based on the user's location in a NextJs application?

I have a NextJs 12 application with URLs domain.com and domain.com/es. We implemented the OneTrust cookie banner in _document.ts as shown below: <Head> <Script id="one-trust" strategy="befor ...

Creating input fields in Vue 3: Best practices

I am looking to create an input field that automatically removes entered characters if they do not match a specific pattern. Here is the template: <input type="text" :value="val" @input="input" /> And here is the ...

Button-click scrolling is our featured feature!

One interesting feature on my website is a button (within a div-element) located in the bottom-right corner. I am now looking to enhance this by adding a jQuery function that enables the user to scroll down the page incrementally simply by clicking and hol ...

The issue of JQuery mobile customizing horizontal radio buttons failing to function on physical devices has been identified

Not long ago, I posed a query on Stackoverflow regarding the customization of horizontal jQuery-mobile radio buttons. You can find the original post by following this link How to customize horizontal jQuery-mobile radio buttons. A developer promptly respon ...

Creating a custom loading screen with three.js and jsonLoader: A step-by-step guide

My project involves loading a significant number of texture files and models, and I'm looking for a way to implement a status bar or loading screen during this process. Any tips or guidance on how to achieve this would be greatly appreciated. Thank y ...

Is there a way to modify the state following a sorting operation?

How can I properly update the state after sorting by salary? state = { workers: [ {name: 'Bob', surname: 'Meljanski', salary: 5140}, {name: 'Michel', surname: 'Hensson', salary: 5420}, {n ...

The getStaticProps() function is failing to send data over to the components

I am currently learning how to use Next.js by following the guide on nextjs.org. My question is, when I use the getStaticProps function, it seems to fetch and log the data correctly inside the function. However, when I pass the data (which is the props ob ...

Not all API results are being displayed by the Nextjs API function

I am facing an issue with rendering all the returns from the API in my Next.js application. The API, which is created in Strapi, is only displaying 1 out of the 3 possible returns. I am a beginner when it comes to using APIs and I suspect that the issue li ...

Utilizing an automated file retrieval system in the absence of database or website access

I'm faced with a challenge of having to download a file automatically when a user clicks the "ok" button on a website. Unfortunately, I only have access to view the site and do not have access to the database or source code. I'm unsure of how and ...