Utilizing plane geometry for chunking in THREE.js

My goal is to create a world that generates infinitely, similar to how Minecraft operates, using chunks that appear and disappear based on the player's location. I am utilizing a plane that generates points through a combination of Perlin and Simplex noise.

However, when I load these points into the world, all the chunks end up looking the same. This happens because I am using the same geometry for each one. I've attempted to use object.matrixAutoUpdate = false; and object.updateMatrix();, but it hasn't made a difference. I also tried assigning different geometries to each chunk, but this caused a drop in performance whenever new chunks were loaded.

Below is the complete code snippet:

function updateChunk() {
    // Clear chunks
    while(ground.children.length > 0){ 
        ground.children[0].geometry.dispose()
        ground.remove(ground.children[0]); 
    }

    let size = (game.chunk.render * 2) + 1
    let sX = (Math.floor(plane.position.x / 1000) * 1000) - Math.floor((size / 2) * 1000)
    let sY = (Math.floor(plane.position.z / 1000) * 1000) - Math.floor((size / 2) * 1000)

    ground.position.set(sX, 0, sY)

    for(let y = 0; y < size; y++) {
        for(let x = 0; x < size; x++) {
            let g = new THREE.Mesh(geometry.clone(), material);
            let startX = ((sX / 1000) + x) * 100
            let startY = ((sY / 1000) + y) * 100
            let currentChunk = createChunk(startX, startY)

            //Setup Terrain
            for(let y2 = 0; y2 < 101;y2++) {
                for(let x2 = 0; x2 < 101; x2++) {
                    g.geometry.vertices[(y2 * 101) + x2].z = currentChunk[x2 + ',' + y2]
                }
            }

            g.rotation.x = Math.PI / -2
            g.position.set(x * 1000, 0, y * 1000)
            g.matrixAutoUpdate = false;
            g.updateMatrix();
            ground.add( g );
        }
    }
}
function createChunk(startX, startY) {
    let chunk = []
    for(let y = 0; y < 101; y++) {
        for(let x = 0; x < 101; x++) {
            chunk[x + ',' + y] = Math.abs(noise.perlin2((x + startX) / 100, (y + startY) / 100)) * 200;
        }
    }
    return chunk
}

Answer №1

I finally came up with a straightforward solution that should have been obvious to me earlier. I decided to pre-generate 25 geometries (5x5 chunks) and assign an ID to each one. As the player moved between chunks, the geometry vertices would reset and be added to a list of unused geometries. Then, when it was time to load a new chunk, a function would select an available ID from the list of unused geometries.

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

Center-align the table element

I've been struggling to center align this table element, specifically the one containing the square, but nothing seems to be working. Can anyone lend a hand in fixing this issue? <table> <tbody> <tr> <td>TURKEY - SU ...

Sending input values from textboxes to the Controller

I currently have the following code snippets: Home Controller: public IActionResult Index() { return View(); } public ActionResult Transfer() { string path = @Url.Content(webRootPath + "\\SampleData\\TruckDtrSource.json&q ...

The one-time binding notation does not seem to be functioning as expected in AngularJS version 1.6.4

For our application, we are utilizing AngularJS 1.6.4 to display a large number of rows on a single page. However, when it reaches around 7K entries, the page starts hanging. To tackle this issue, we have opted for one-time binding for those specific pages ...

Under what circumstances would you need to manually specify the displayName of a React component?

After coming across an article (linked here: https://medium.com/@stevemao/do-not-use-anonymous-functions-to-construct-react-functional-components-c5408ec8f4c7) discussing the drawbacks of creating React components with arrow functions, particularly regardi ...

Tips for maintaining a persistent login session in Gmail with Puppeteer and Node.js

I'm trying to access a pre-signed gmail account, following the guidance provided by this answer from user wolfy. However, I noticed that it logs me out after a while or when multiple instances are opened with the same cookies, requiring me to re-enter ...

Converting objects to arrays in AngularJS and Ionic: A simple guide

In the scenario where I have an object structured like this: {first: "asdasd", second: "asdas", third: "dasdas", four: "sdasa"}, my objective is to convert this object into an array. if(values){ var first=values.first; var second=values.second; var ...

What is the best way to activate a click event within an ng-repeat loop in AngularJS

Is there a way to trigger an event click handler in angular where clicking the button will also trigger the span element? I've tried using the nth-child selector without success. Any suggestions on how to achieve this? I also attempted to use jQuery s ...

What is the best way to ensure that two Node processes do not insert duplicate database records when running concurrently?

My Lambda function receives a high volume of events simultaneously, causing AWS to spin up multiple instances to handle the load. The function written in Node.js uses Knex to interact with a Postgres database, checking if a record with a specific ID exists ...

Tips for creating a versatile generic function in javascript that covers all arguments sizes

When working with node.js, a tcp server typically has several methods for listening: server.listen(port, [host], [backlog], [listeningListener]) server.listen(path, [listeningListener]) server.listen(handle, [listeningListener]) In the context of creatin ...

Is there a way to improve the efficiency of this jQuery/JavaScript snippet by rewriting it?

I've attempted at least 25 variations of this code to make it more efficient, but each one seems to cause issues. In essence, I am assigning different classes to elements in order to trigger a css/keyframes animation when the window width is 1025px o ...

Will cancelling a fetch request on the frontend also cancel the corresponding function on the backend?

In my application, I have integrated Google Maps which triggers a call to the backend every time there is a zoom change or a change in map boundaries. With a database of 3 million records, querying them with filters and clustering on the NodeJS backend con ...

Sending files using AJAX without FormData in Internet Explorer 9

Unfortunately, IE9 does not support FormData, making file uploads via XMLHttpRequest a more challenging task. Is there a workaround for this issue? I've come across mentions of using iFrames, but the process seems complex and unclear on how to transf ...

Using v-for with TailwindCSS animations seems to cause issues

I'm currently working on implementing a list of pop-up messages in the upper right corner of the screen. These messages should disappear when clicked and include a slide-fade transition effect. The transition animation works fine when there is only o ...

Incorporate an Ajax response script with a Django HttpResponse

How can I pass the ajax response obtained from the view to the template using HttpResponse? I'm unsure of the process. view.py analyzer = SentimentIntensityAnalyzer() def index(request): return render(request, "gui/index.html") @csrf_exempt d ...

The property 'titulo' of 'actividad' cannot be destructured because it is currently undefined

I'm currently utilizing the useParams hook to fetch a custom component. It successfully renders the id, but nothing more. Here's a snippet of my code: import React, { useState } from "react"; import { Link } from "react-router-dom ...

Creating a hierarchical JSON format for a nested commenting system

I have a JSON data representing a multi-level comment system as shown below: [{ "thread_id": 2710, "parent_id": "", "username": "string", "comment": "string", "postdate": "2017-06-09T07:12:32.000Z", "id": 1 }, { "thread_id": 2710, "parent_ ...

Activate PHP using javascript

My PHP script is designed to capture a user's IP address, current webpage, screen resolution, and Date/Time when they visit my website. To implement this tracking functionality on another website, I plan to insert the following line of code: <scr ...

Once the ajax request is finished, load only the <script> tags that have specific ids

I'm currently implementing infinite-scroll to dynamically load more content which includes <script> tags that need to be executed. To achieve this, I have created the following code as an ajax-callback: JS on load ajax callback: function a ...

Pause and submit the form only when the Observable has finished

My application features a 'new trip' form that allows users to input participant names and submit the form to create the trip. Upon submission, I perform a query on a Firebase database with these names to retrieve the corresponding IDs of the par ...

What causes Firefox's CPU to spike to 100% when a slideshow begins that adjusts the width and left coordinates of certain divs?

Seeking Advice I'm in need of some help with identifying whether the code I'm working on is causing high CPU usage in Firefox or if it's a bug inherent to the browser itself. The situation is getting frustrating, and I've run out of so ...