2017-02-02 36 views
0

我創造粒子與three.js所隨機他們定位:設置界限

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); 
} 

然後在我的requestAnimationFrame更新功能,我移動的粒子:

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

哪有我爲運動帶來一些限制?即當粒子到達屏幕邊緣時,我想將它們「反彈」回來。

+0

我可能會存儲每個粒子'direction'載體和'velocity'值。對於每一幀,按其方向和速度更新粒子的位置。如果粒子擊中或穿過邊界邊界,重新計算方向和速度,以便下一次更新將以新方向發送。 – TheJim01

回答

1

最好是有方向和速度爲每個粒子。方向始終是標準化的THREE.Vector3()

然後爲你的粒子代碼將是這樣的:

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(); // a normalized vector with random values for x,y 
    particle.velocity = Math.random() * 50; // speed is 50 units per second 
    particles.push(particle); 
} 

假設,您使用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); 

要設置合適的速度(50個我們單位每秒),我們將需要THREE.Clock()及其.getDelta()方法:

var clock = new THREE.Clock(); 
var shift = new THREE.Vector3(); //we will re-use it in the animation loop 
var delta = 0; // we will re-use it in the animation loop 

而在動畫循環中,我們將做到這一點:

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

    particles.forEach(function(p) { 

    if (p.x > sizeX/2 || p.x < -sizeX/2) { // it's also can be like if (Math.abs(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)); // here we re-use the `shift` vector 
    }) 

    points.geometry.verticesNeedUpdate = true; // important, if you won't set it to true you won't get your particles moving 

所以這是它。

jsfiddle例如

PS。如果您想使用BufferGeometry,那麼你可以參考這個很好SO answer