Infinite forward grid movement with the power of three.js

Synthwave Mesh

I've been experimenting with creating a moving blue grid effect in three.js, where the grid appears to be continuously advancing forward as if approaching the sun. I haven't been able to find any examples on how to achieve this specific effect. Something similar to what is shown in this GIF:

One approach I tried involves using the following code:

   lines1.position.z = Math.cos( time ) * 0.75 + 1.25;

This snippet showcases the creation of the grid using THREE.Line:

for (var i = -size; i <= size; i+=steps)
{
    geometry.vertices.push(new THREE.Vector3(-size, - 0.10,i));
    geometry.vertices.push(new THREE.Vector3(size, -0.10,i));

    geometry.vertices.push(new THREE.Vector3(i, - 0.10,-size));
    geometry.vertices.push(new THREE.Vector3(i, - 0.10,size));
}

var lines1 = new THREE.Line(geometry, material, THREE.LineSegments)


scene.add(lines1);

Answer №1

Great query!

To tackle this challenge, I devised a solution using THREE.GridHelper() in conjunction with THREE.ShaderMaterial():

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 10, 50);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var division = 20;
var limit = 100;
var grid = new THREE.GridHelper(limit * 2, division, "blue", "blue");

var moveable = [];
for (let i = 0; i <= division; i++) {
  moveable.push(1, 1, 0, 0); // only allow movement of horizontal lines (1 - point is movable)
}
grid.geometry.addAttribute('moveable', new THREE.BufferAttribute(new Uint8Array(moveable), 1));
grid.material = new THREE.ShaderMaterial({
  uniforms: {
    time: {
      value: 0
    },
    limits: {
      value: new THREE.Vector2(-limit, limit)
    },
    speed: {
      value: 5
    }
  },
  vertexShader: `
    uniform float time;
    uniform vec2 limits;
    uniform float speed;
    
    attribute float moveable;
    
    varying vec3 vColor;
  
    void main() {
      vColor = color;
      float limLen = limits.y - limits.x;
      vec3 pos = position;
      if (floor(moveable + 0.5) > 0.5){ // check if a point is moveable
        float dist = speed * time;
        float currPos = mod((pos.z + dist) - limits.x, limLen) + limits.x;
        pos.z = currPos;
      } 
      gl_Position = projectionMatrix * modelViewMatrix * vec4(pos,1.0);
    }
  `,
  fragmentShader: `
    varying vec3 vColor;
  
    void main() {
      gl_FragColor = vec4(vColor, 1.);
    }
  `,
  vertexColors: THREE.VertexColors
});

scene.add(grid);

var clock = new THREE.Clock();
var time = 0;

render();

function render() {
  requestAnimationFrame(render);
  time += clock.getDelta();
  grid.material.uniforms.time.value = time;
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>

Answer №2

If you're looking for a simpler way to add texture to your project, consider trying out textures in Three.js. Check out this interesting example:

Using textures can be a more efficient alternative to working with numerous vertices and managing their movements.

Best regards,

Gerdon

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

How to Retrieve a Specific Line with jQuery

Could jQuery be used to retrieve the offset of the first letter in the 5th visual line of a block's content? I am referring to the visual line determined by the browser, not the line seen in the source code. ...

reasons why the keypress event may not be triggered

Hello there, I am trying to create a function that simulates pressing the 'tab' key. The function is supposed to restrict input within specific ranges and return the cursor to another range once the limit is reached. Additionally, if a user input ...

What is the output of the createRange() function?

I am encountering an issue with my code that is causing the highlighted text to always appear at the end of the page when it pops up. Is there a way to make it show in the middle of the line or below the selected text instead? I have included the current ...

Monitoring changes to localstorage in AngularJS

How can I monitor changes to localStorage using $watch? I have created a factory to simplify setting and getting values .factory('$localstorage', ['$window', function($window) { return { set: function(key, value) { ...

Is there a way to convert datetime format to date in a Vue component?

With my Vue component set up like this: <template> ... <td>{{getDate(item.created_at)}}</td> ... </template> <script> export default { ... methods: { getDate(datetime) { ...

Node.js and Socket.IO: Managing responses

In a unique scenario, the web page is initially served using HTTP. When the submit button is clicked, data is sent to the server and multiple web services are executed, which may take some time. The challenge is to quickly display the response page and the ...

Can anyone explain to me why the data I'm passing as props to the React functional component is displaying as undefined?

I have encountered an issue with a pre-made React component where I am unable to see the data being passed as props when I console log it. I am unsure if I am passing the prop correctly, as I have used the same prop successfully in other class-based comp ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

angular2 and ionic2 encounter issues when handling requests with observable and promises

I am attempting to trigger an action once a promise request has been resolved, but I'm having trouble figuring out how to achieve this. After doing some research, I learned that Ionic2 storage.get() returns a promise, and I would like to make an HTTP ...

Localizing HTML number input values is not functioning properly

When using an HTML number field, I encountered the following error: The specified value "101,5" is not a valid number. The value must match the regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)? I am trying to co ...

What does a transformed SVG element's getBoundingClientRect() method return?

Today I experimented with the effects of using getBoundingClientRect() on an SVG element that has undergone rotation. Evaluation: The outcome revealed: Chrome, Safari, Opera, and IE seem to calculate the local (untouched) bounding box of the element, ...

JavaScript Object Notation, asynchronous JavaScript and XML, and Active Server Pages

In my client-side file, there is an ajax call within jQuery that sends JSON data to a WebMethod on the server-side. The code snippet below demonstrates how it can be achieved: Server-side WebMethod (C#) [System.Web.Services.WebMethod] public static strin ...

Storing past entries in a local storage using JavaScript

Currently, I am developing a JavaScript program that involves 3 input boxes. The program is designed to display whatever is typed into each input box on the page. To store and re-display previous submissions, I have implemented local storage. However, I en ...

Exploring Twig variables in Node.js with the node-twig package

Despite following the documentation meticulously, and experimenting with various methods, I am still unable to achieve success. I have attempted using the code snippet below, trying to reference the variable in the main file like this: // None of the opti ...

JQuery is not able to render Hindi content properly

I am attempting to showcase some Hindi words using JQuery because these are essential contents that need to be displayed on every page of the website. Please note that this is a static website built with HTML and JQuery/JavaScript. Below is my JS file: in ...

Verify the ng-if condition for a specific value and display an alternative option if the condition is not

When obtaining a response from the server in JSON format (containing color.mix and color.pure), it is passed directly to the template. In this template, I need to display a value if it exists or show another value if it does not. <span ng-if="color.mix ...

Error with JSON data from the Twitch TV API

I am having trouble with the Twitch API. When a streamer is live, I work with the "Stream" property, but if they are not streaming, I need to refer to another link. I use the getJSON function to fetch the necessary API link and work with it. However, my lo ...

Utilizing webpack to import both d3 and d3-cloud libraries

I've been attempting to integrate d3 and d3-cloud (for word cloud) into my AngularJs(v - 1.4) app by using: import d3 from 'd3' import d3Cloud from 'd3-cloud'. However, when trying to use d3-cloud with d3.layout.cloud(), ...

Is there a correct way to accomplish this task? How could I go about achieving it?

Currently, I am delving into the world of react. While following along with some video tutorials, I encountered a roadblock in the request.js file. The issue popped up during the build process ./src/Row.js Line 16:45: 'fetchUrl' is not define ...

Ensure that the response interceptor is executed only once, even when multiple API calls are

I currently have an interceptor set up as follows axios.interceptors.response.use(undefined, err=> { const error = err.response; console.log(error); if (error.status===401 && error.config && !error.config.__isRetryRequest) { ...