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