Creating particle animations using Three.js along a curved path

I'm attempting to create an animation where particles move along a specific path, similar to the one showcased in this Chrome experiment:

Upon examining the source code of the aforementioned project, I've discovered that they utilize a predefined curve method called .getPoints() to generate approximately 30 points which define their lines.

Are there any other examples available that demonstrate what I'm trying to achieve? Is there a more efficient method for obtaining points on a line as opposed to using the .lerp() method repeatedly to acquire 30 points? Would it be advisable to incorporate TWEEN animations instead?

Any guidance or assistance on this matter would be greatly appreciated.

Answer №1

I have discovered a solution that seems to work well, although I am not sure if it is the optimal one.

If you want to see a demonstration, you can check it out on JsFiddle: https://jsfiddle.net/L4beLw26/

//To begin with, create the line along which we want to animate the particles
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(-800, 0, -800));
geometry.vertices.push(new THREE.Vector3(800, 0, 0));

var line = new THREE.Line(geometry, material);
var startPoint = line.geometry.vertices[0];
var endPoint = line.geometry.vertices[1];
scene.add(line);

//Then, generate approximately 30 animation points along the line
var animationPoints = createLinePoints(startPoint, endPoint);

//Add particles to the scene
for ( i = 0; i < numParticles; i ++ ) {
  var desiredIndex = i / numParticles * animationPoints.length;
  var rIndex = constrain(Math.floor(desiredIndex),0,animationPoints.length-1);
  var particle = new THREE.Vector3();
  particle = animationPoints[rIndex].clone();
  particle.moveIndex = rIndex;
  particle.nextIndex = rIndex+1;
  if(particle.nextIndex >= animationPoints.length )
    particle.nextIndex = 0;
  particle.lerpN = 0;
  particle.path = animationPoints;
  particleGeometry.vertices.push( particle );
}

//Define particle material
var pMaterial = new THREE.ParticleBasicMaterial({
  color: 0x00FF00,
  size: 50,
  map: THREE.ImageUtils.loadTexture(
    "assets/textures/map_mask.png"
  ),
  blending: THREE.AdditiveBlending,
  transparent: true
});

var particles = new THREE.ParticleSystem( particleGeometry, pMaterial );
particles.sortParticles = true;
particles.dynamic = true;
scene.add(particles);

//Update function for each particle animation
particles.update = function(){
  // var time = Date.now()
  for( var i in this.geometry.vertices ){
    var particle = this.geometry.vertices[i];
    var path = particle.path;
    particle.lerpN += 0.05;
    if(particle.lerpN > 1){
      particle.lerpN = 0;
      particle.moveIndex = particle.nextIndex;
      particle.nextIndex++;
      if( particle.nextIndex >= path.length ){
        particle.moveIndex = 0;
        particle.nextIndex = 1;
      }
    }

    var currentPoint = path[particle.moveIndex];
    var nextPoint = path[particle.nextIndex];

    particle.copy( currentPoint );
    particle.lerp( nextPoint, particle.lerpN );
  }
  this.geometry.verticesNeedUpdate = true;
};

function createLinePoints(startPoint, endPoint){
  var numPoints = 30;
  var returnPoints = [];
  for(i=0; i <= numPoints; i ++){
    var thisPoint = startPoint.clone().lerp(endPoint, i/numPoints);
    returnPoints.push(thisPoint);
  }
  return returnPoints;
}

function constrain(v, min, max){
  if( v < min )
    v = min;
  else
    if( v > max )
      v = max;
  return v;
}

Lastly, make sure to include the following line within the animation loop:

particles.update();

Answer №2

It seems like there may be some issues with the snippets not working properly, but I have taken the solution provided by jigglebilly and incorporated it into a complete HTML page where it is functioning correctly. Feel free to check out the working version below:

Particle Test

<script src="../js/three.js"></script>

<script type="text/javascript">
    // JavaScript code for particle animation goes here
</script>

This implementation utilizes three.js R67.

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

Ajax loaded scripts are unable to access global variables

Index.html <script> let bar = 1; </script> This html page is being loaded multiple times on the page using AJAX: article.html <script> if (bar === 1) { // perform a task } // Error: bar is not defined </script> Bar is a simple ...

Plupload is not compatible with ng-dialog

I'm currently attempting to integrate plupload into a modal window that is generated by ng-dialog. Here is the code I am using: $scope.showManager = function(){ ngDialog.open({ template: '/template/fmanager.html', controller: &apo ...

The Material UI Drawer stays closed despite the state being set to true

Currently, I am in the process of developing a WebApp utilizing React and Material UI. Despite following numerous tutorials on implementing the Drawer component and poring over the documentation, I am still struggling to grasp its functionality. Even thou ...

Tips for handling Ajax urlencode in PHP

I'm facing an issue with a problem and need some assistance to resolve it. Currently, I am attempting to utilize Ajax urlencode in PHP, but the POST content is not being displayed by PHP as expected when HTML is sent directly to PHP. The following c ...

Node/Express: Detecting PDF Data Size of 0

Currently, I am facing a challenge with retrieving a PDF file from my Google Cloud Storage. The URL for the PDF is stored in MongoDB entry which is causing issues when sending it to the client. It seems like the data being read is empty due to some async o ...

Is there a way to extract the HTML source code of a website using jQuery or JavaScript similar to PHP's file_get_contents function?

Can this be achieved without a server? $.get("http://xxxxx.com", function (data) { alert(data); }); I have tried the above code but it seems to not display any output. ...

AngularJS filtering with multiple conditions

My ng-repeat list is currently displaying a collection of objects with a filter applied to only show objects inserted today. Here is how it looks: <div class="row msf-row" ng-repeat="record in recordlist | filter: record.date = dateJson"> Whi ...

Developing a Chrome browser extension tailored for parsing unique file formats

Currently, I am working on developing a compiler for a unique conditional formatting language. My aim is to enable the capability of opening files in my language directly in Chrome by simply double-clicking on them in File Explorer (I am currently using Wi ...

Merging Angular with jQuery: Organizing jQuery into a distinct file leads to the error message 'Property 'top' cannot be read because it is undefined.'

My project is based on AngularJS, and I've been trying to incorporate a jQuery code for a sticky sidebar feature. Strangely enough, when I tested my code on Plunkr, it works perfectly fine. However, when I try to implement it in my actual project, it ...

Managing checkbox inputs within a MEAN stack application

As someone who is brand new to the MEAN stack, I've been experimenting with saving an array of checkbox values and retrieving them from MongoDB. I've set up a clear schema for embedded arrays using Mongoose, but I'm struggling with how to in ...

What is the process of using AJAX, JavaScript, and HTML to submit data to a remote

I need help with sending data from an HTML page to a server. I have a JSON example below that illustrates what I want to achieve. On my HTML page, I have a question label and four options (A, B, C, D) as radio buttons. After clicking the send button, I ...

Attempting to transfer user information to MongoDB using AngularJS and Node.js

Greetings everyone! I am currently working on a template and trying to develop a backend for it, starting with the registration form. Despite having some kind of connection between my mongodb and my app, data is not being sent to the database. Here is the ...

Discovering whether x is equal to any value within an array using JavaScript

I am seeking a way to modify my current if statement, which looks like this: if (x==a||x==b||x==c||x==d||x==e) { alert('Hello World!') }; Is there a method to test whether x matches any of the values in an array such as [a,b,c,d,e]? Your as ...

Delayed callback on blur

I am developing an AutoComplete feature in React that displays a list of suggested completions as the user types into a text box. When a suggestion is clicked, it should trigger a callback function, and the dropdown should disappear when the text box loses ...

How can I use ReactJS to find the nearest five locations in order from closest to farthest?

I'm in the process of creating a website for searching nearby locations. I am facing an issue where I want to display the 5 closest locations from my current location in ascending order, but I keep getting the same location result. I need these locati ...

What is the best way to incorporate a fade in effect when a user clicks on a JavaScript dropdown menu?

I found a helpful code snippet on GitHub at this link which allowed me to easily create a dropdown menu. However, I wanted to add a Fade in and out effect when the menu is clicked. Here is my attempted implementation, but unfortunately, the fadeIn functi ...

AngularJS call to the web service

I am facing an issue where I do not receive any response upon clicking the button. <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js"></script> <sc ...

Avoiding console errors when a REST call fails

After conducting some research, it appears that achieving this is not possible. Therefore, I decided to seek advice. My current task involves making a REST GET call to check for the existence of a folder. If the folder does not exist, I create a new one; ...

Creating a custom toJSON function for a property declared using Object.defineProperty

Let's consider a scenario where we have an object with a specific property that is meant to reference another object, as shown below: Object.defineProperty(parent, 'child', { enumerable: true, get: function() { return this._actualCh ...

What is the process for defining default prop data in Next.js?

Currently, I am in the process of developing a React/Next app with CRUD functionality. In regards to the update form, I have included the code below which is responsible for fetching existing data and updating it via an API. However, there seems to be a ma ...