Establishing limits on the motion of particles

I'm currently using three.js to generate particles and place them in random positions:

for( var i = 0; i < particleCount; i++ ){
  var pX = Math.random() * 100-50;
  var pY =Math.random() * 100-50;
  var pZ = Math.random() * 100-50;
  particle = new THREE.Vector3(pX,pY,pZ);
  particle.velocity = new THREE.Vector3(Math.random(), Math.random(), pZ);
  particles.vertices.push(particle);
}

Next, in my requestAnimationFrame update function, I'm adjusting the particle's positions:

for (var i = 0; i < particleCount; i++) {
    var particle = particles.vertices[i];
    particle.y += particle.velocity.y*speed;
    particle.x += particle.velocity.x*speed;
  }

Is there a way to set boundaries for the movement? For example, when a particle reaches the edge of the screen, I'd like it to bounce back.

Answer №1

It's important to assign a specific direction and velocity to each particle. The direction should always be a normalized THREE.Vector3().

Here is an example of how to code your particles:

var particles = [];
var particleCount = 100;
var sizeX = 300;
var sizeY = 200;
var sizeZ = 100;

for (var i = 0; i < particleCount; i++) {
  var pX = Math.random() * sizeX - sizeX / 2;
  var pY = Math.random() * sizeY - sizeY / 2;
  var pZ = Math.random() * sizeZ - sizeZ / 2;
  particle = new THREE.Vector3(pX, pY, pZ);
  particle.direction = new THREE.Vector3(Math.random() - .5, Math.random() - .5, 0).normalize(); // setting the direction with random values for x,y
  particle.velocity = Math.random() * 50; // speed set to 50 units per second
  particles.push(particle);
}

If you are using THREE.Points():

var geometry = new THREE.Geometry();
geometry.vertices = particles;

var points = new THREE.Points(geometry, new THREE.PointsMaterial({
  size: 5,
  color: "red"
}));
scene.add(points);

To adjust the speed (50 units per second), we can utilize THREE.Clock() along with its .getDelta() method:

var clock = new THREE.Clock();
var shift = new THREE.Vector3(); //will be used in the animation loop
var delta = 0; //will be used in the animation loop

In the animation loop, we will include the following code:

  delta = clock.getDelta(); // get time period between frames (in seconds)

  particles.forEach(function(p) {

    if (p.x > sizeX / 2 || p.x < -sizeX / 2) {
      p.direction.x = -p.direction.x;
    }
    if (p.y > sizeY / 2 || p.y < -sizeY / 2) {
      p.direction.y = -p.direction.y;
    }
    if (p.z > sizeZ / 2 || p.z < -sizeZ / 2) {
      p.direction.z = -p.direction.z;
    }

    p.add(shift.copy(p.direction).multiplyScalar(p.velocity * delta)); 
  })

  points.geometry.verticesNeedUpdate = true; 

That's the gist of it.

jsfiddle example

PS If you prefer to use BufferGeometry, check out this informative SO answer

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

Searching for "unique elements" using AngularJS ng-repeat

I am trying to organize a list by category, but the challenge is that each category input is customized and can be added by any user in the list. My initial attempt involved using ng-repeat to filter out duplicate values (as seen in the code snippet uniqu ...

Storing client-requested data locally

Is it possible to use JavaScript to make an AJAX request to fetch data from a server, then prompt the user to save this data on their computer for later access outside of the browser session? Can this saving functionality be achieved without using a Flas ...

Update the class of the element that is currently selected using jQuery and the `this` keyword

Is there a way to change the class on hover only for the current element using 'this'? The code I have changes classes for all elements, but I need it to work individually. Here is the code snippet I'm currently using: https://codepen.io/ky ...

The $scope within the $ionicplatform is not functioning as expected

I've been working on an application, but it doesn't seem to be functioning correctly. Typically, when we add a value to the scope, I expect it to update in the application. Here is the snippet from index.html: <body ng-app="starter"> <i ...

Issue with scrolling to the bottom of collapsed sections in Bootstrap

I have a bootstrap collapse panel and I've added a toggle link at the bottom to allow users to expand and collapse the content with a click. The Issue My problem arises when the menu expands, causing it to scroll all the way to the bottom of the pag ...

Emit Observables within deeply nested callback functions

Hey there! I'm currently working on a web app using Angular2/4 and I've encountered an issue with Observables. My goal is to call a function within a component and then have some code executed once that function completes. Here's the releva ...

Manipulating the visibility of components by toggling on click events according to the existing state in ReactJS

Disclosure: I am still getting familiar with ReactJS I'm currently working on incorporating a dialog window for selecting a country/language on the initial page of my application. Here's the concept: There's a small flag button in the to ...

How can I prevent my code from resetting every time a state update occurs?

https://i.sstatic.net/snSGl.pngI've coded a program that creates a 10x10 grid with 5 boxes of varying sizes. When you click on a box, an x is added to its content and the turn state is set to false. The issue arises when the code re-runs after each s ...

Leveraging Async / Awaits with Promise

Within my code, I have a specific promise chain that follows this structure: myPromise() .then(getStuffFromDb) .then(manipulateResultSet) .then(manipulateWithAsync) .then(returnStuffToCaller) An issue arises when working within the mani ...

Tips for concealing a tab upon selecting an option from a dropdown menu

<ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#song">Song</a></li> <li id="image-tab"><a href="#image" data-toggle="tab">Image</a></li> </ul> <div class="tab-cont ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

Tips on showing a success notification following form submission in HTML

I have crafted this code utilizing a combination of bootstrap, python, and html. I have omitted the css portion for brevity, but I can certainly provide it if necessary. My aim is to be able to send an email using smtplib and flask, with the added function ...

Ways to activate javascript following a PHP submission?

It's a bit tricky to explain. function m(val){ var element=document.getElementById('othermethod'); if(val=='others') element.style.display='block'; else element.style.display=&apo ...

Several socket.io sessions have been initiated

I'm fairly new to working with node.js and currently attempting to set up a server using socketio to send messages to the frontend (React). However, when running the server and multiple connections are being established, I encounter the following outp ...

Navigating the challenges presented by CORS (Cross-Origin Resource Sharing) and CORB (Cross-Origin Read Blocking) when utilizing the FETCH API in Vanilla Javascript

Looking to update text on a website using data from a JSON file on another site? This scenario is unique due to restrictions - can't use JQuery or backend elements like Node/PHP. Wondering if vanilla JavaScript can solve the problem? While some worka ...

Issue with Canvas.doDataUrl not functioning properly in presence of an image on canvas

It seems like the code I have tried only works for local images. Can someone share a working code snippet for this? Here is what I've attempted: var base_image = new Image(); base_image.src = ("/img.png"); base_image.onload = function(){ var co ...

Using MediaQuery from react-responsive to selectively hide individual JSX attributes

I have a button element that includes both the Profile Picture and the Info, which consists of the first name and last name. My goal is to hide only the profile picture (profileImageProps={profileImageAndBasicInfoProps.profileImageProps}) when the screen ...

Stylus remains undefined even after a successful npm installation

I've been following a tutorial to learn more about node.js, but I keep encountering a strange error. After running npm install stylus, I receive the following output: npm http GET https://registry.npmjs.org/stylus npm http 304 https://registry.npmjs. ...

Exploring the ins and outs of webpage loading speed

I am working on writing JavaScript code that includes a button to open a webpage of my choice. I now want to understand how to detect when the page I called is finished loading. Any suggestions or ideas on this topic? I apologize if my explanation was no ...

Retrieve the content from paragraph elements excluding any text enclosed within span tags using the Document.querySelector method

Exploring the following element structure: <p> <span class="ts-aria-only"> Departure </span> RUH <span class="ts-aria-only">&nbsp;Riyadh</span> </p> In an attempt to extract the text RUH, it has been disc ...