Moving the grid in threejs when the camera approaches its edge: A guide

Is there a way to create an infinite grid plane without having to generate a massive grid each time?

I attempted adjusting camera.position.z and grid.position.z, but the grid's z position remains at 0 when moving the camera.

Looking for functionality similar to a chase-camera scenario like this example (), but with a never-ending floor.

Any assistance on this matter would be greatly appreciated.

Answer №1

This method may not be the ultimate solution, but it serves as a good starting point.

By utilizing the THREE.GridHelper() function, you have the ability to control the direction of its lines. By examining the source code of the helper, I discovered the sequence of points for the lines in its geometry. The key concept is to understand how each point corresponds to a specific line, enabling the manipulation of its direction. With both vertical and horizontal lines present, adjustments can be made on the x-axis for vertical lines and the z-axis for horizontal lines. The order of vertices follows this pattern:

start_point_horizontal, end_point_horizontal, start_point_vertical, end_point_vertical,... 

and this pattern continues throughout.

To facilitate this process, an attribute is assigned to each vertex to determine whether it belongs to a vertical or horizontal line.

  var hv = new Float32Array(plane.geometry.attributes.position.count);

  for (var i = 0; i < plane.geometry.attributes.position.count; i+= 4) {
    hv[i+0] = 0;
    hv[i+1] = 0;
    hv[i+2] = 1;
    hv[i+3] = 1;
  }

  plane.geometry.addAttribute("horivert", new THREE.BufferAttribute(hv, 1));

Several global variables are required for this approach:

var clock = new THREE.Clock();
var direction = new THREE.Vector3();
var speed = 1;
var size = 10;
var delta = 0;
var shift = new THREE.Vector3();
var plane; // reference to our GridHelper

The animation loop brings everything together:

  delta = clock.getDelta();

  shift.copy(direction).normalize().multiplyScalar(delta * speed);
  var arr = plane.geometry.attributes.position.array;
  for(var i=0; i < plane.geometry.attributes.position.count; i++)
  {
    var hv = plane.geometry.attributes.horivert.array[i];
    if (hv == 1) // when dealing with a point on a vertical line, we adjust it on the x-axis
        {
        arr[i * 3 + 0] += shift.x;
        if (arr[i * 3 + 0] < -size)
            arr[i * 3 + 0] = size - Math.abs(-size - arr[i * 3 + 0]);
        if (arr[i * 3 + 0] > size)
            arr[i * 3 + 0] = -size + Math.abs(arr[i * 3 + 0] - size);
      }
      else //if it's a horizontal line point, we move it along the z-axis
      {
        arr[i * 3 + 2] += shift.z;
        if (arr[i * 3 + 2] < -size)
            arr[i * 3 + 2] = size - Math.abs(-size - arr[i * 3 + 2]);
        if (arr[i * 3 + 2] > size)
            arr[i * 3 + 2] = -size + Math.abs(arr[i * 3 + 2] - size);
      }
    }
    plane.geometry.attributes.position.needsUpdate = true;

If a point reaches a lower limit, it wraps around to the upper limit, and vice versa.

I created a jsfiddle example from scratch to demonstrate the implementation.

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

Changing the fill color of an SVG pattern remains unchanged

I have been working with Vue.js to create SVGs with shape patterns as background. The patterns themselves are functioning correctly, but I am encountering an issue when attempting to dynamically change the color of the pattern filling by passing props. D ...

Issue with React hook state persistence in recursive function

I implemented a recursion custom hook that utilizes a setTimeout function to provide 3 chances for an operation. Once the chances run out, the recursion should stop. However, I encountered an issue where the setTimeout function is not properly decrementin ...

Deactivate and circumvent Angular routing outside of the specified route URL

I am looking for a way to disable and bypass Angular routing when I have static pages or PHP-rendered views in my hybrid PHP and AngularJS app. Instead of being redirected by Angular's routing, I want to perform a full page reload to the routed link o ...

Error: Unable to access 'map' property of an undefined variable in NextJS while using getStaticPaths

Currently facing an issue with dynamic routing in my Next.js project. I have a dynamic page [id].js and am trying to fetch data from an API. const res = await fetch(`myAPI`); const resData = await res.json(); const paths = resData.data.map((r) =&g ...

Safari experiencing delays when repeatedly playing audio in quick succession

I'm attempting to overlay a sound on itself when a key is pressed. To achieve this, I discovered that cloning the sound and playing the new instance works: var audioPromise = sound.cloneNode(true).play(); Here is the live example: https://jsfiddle.n ...

The AJAX request sends the <div> element instead of the <button> element

I'm puzzled as to why this ajax call is passing the div id instead of the button id that I intended. <?php while($info = mysqli_fetch_array($sql)) { echo "<tr> <th>" .$info[& ...

Tips for extracting text from a textarea while retaining newline characters:

When using jquery, my goal is to retrieve the text from a textarea element with new lines represented as \n instead of br tags. However, I encountered an issue where Firefox debugger does not display the \n or br characters when I select it and r ...

Enhance your slideshows with React-slick: Integrate captivating animations

I recently built a slider using react slick, and now there is a need to adjust the transition and animation of slides when the previous and next buttons are clicked. I received some advice to add a class to the currently active slide while changing slide ...

The top scrolling behavior on click applies exclusively to the first set of Bootstrap 5 tabs

I am experiencing an issue with my HTML webpage that contains multiple BS5 Nav Tabs. The first tab is not functioning properly, while all the other tabs are working smoothly. When I click on the first BS5 Nav Tab, the page scrolls to the top with the addre ...

Is there a way to identify extensive usage of JavaScript on a webpage using Python, Scrapy, and Selenium?

After creating a Scrapy spider to handle Javascript content on webpages using Selenium, I noticed that it was much slower compared to a traditional Scrapy Crawler. To speed up the process, I am considering combining two spiders: utilizing the common CrawlS ...

Embracing PWAs with subdomains – seamless installation

One of my Progressive Web Applications (PWA) called app A contains a link to another app, app B. Initially, I hosted both apps on the same subdomain (for example: ) and everything worked perfectly - installing app A also installed app B. However, when I a ...

Attempting to loop through a list and create a retrieval function for each item

My goal is to loop through the style tags and create a GET function for each one. The issue I'm facing is that the GET function is being written with a direct reference to 'styleTags[i]' instead of converting it to the appropriate tag. var ...

Bidirectional binding in Angular 2 Custom Directive

I've been working on a custom directive that automatically selects all options when the user chooses "All" from a dropdown. While I was able to get my custom directive to select all options, it doesn't update the model on the consuming component. ...

Altering iframe Content with the Help of Selenium Web Driver

I am looking to update the content of an iframe with new material using Selenium WebDriver. Note: I have attempted the following method: driver.swithTo().frame(frame_webelement); driver.findElement(By.xxx).sendKeys("Mycontent"); While I was able to cle ...

Exploring an unusual HTML structure using Python's Beautiful Soup and urllib for web scraping

While extracting data may not be a challenge, the real issue lies in locating it. My focus is on scraping football data from a website that presents statistics either for all years or for specific seasons. However, despite selecting a particular season, ...

What is the best way to convert an object into an array of objects for use in a select search functionality

I am attempting to map key and value pairs into a single array in order to use them as selectsearch options. I have successfully mapped each item individually, but now I need to combine all the data into one array. How can I achieve this? Here is how I am ...

Content Management System editing plan

Have you ever wondered if there is a structured approach to editing content management systems like Wordpress and Joomla? When it comes to editing aspects such as CSS and JavaScript, what steps do you usually take? Personally, I have been creating files l ...

Storing leaflet marker in Django model for safekeeping

I am working on developing a web application using Django where users can create markers on a map. Currently, I have a JavaScript script that allows users to add markers by clicking on a Leaflet map. window.onload = function () { element = document.get ...

The Android smartphone is experiencing issues with the responsive design not aligning properly on the

I'm encountering difficulties with creating a Viewport that functions properly on an android smartphone. My website is fully responsive, scaling down to 480 pixels wide. At this point, a min-width of 480px is set on the body tag. Initially, my viewp ...

Implementing timeAgo with jQuery (or a similar tool) to display the elapsed time since a user (client) accesses or updates a webpage

https://i.sstatic.net/Y7bzO.png Currently, the timer displayed always shows the actual time instead of phrases like "about a minute ago" or "5 minutes ago". I have tried different solutions without success. //timeago by jQuery (function timeAgo(selector) ...