2017-02-02 1 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; 
    } 

어떻게 할 수 운동에 몇 가지 한계를 소개하겠습니까? 즉 입자가 화면의 가장자리에 도달하면 다시 그 입자를 "바운스 (bounce)"하고 싶습니다.

+0

. 각 프레임에 대해 방향과 속도로 입자의 위치를 ​​업데이트합니다. 파티클이 테두리를 두드리거나 교차하는 경우 방향 또는 속도를 다시 계산하여이 업데이트 또는 다음 업데이트가 새 방향으로 전송합니다. – 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 예를

당신이 BufferGeometry를 사용하려면 PS는, 다음을 참조 할 수 있습니다이 아주 좋은 나는 아마 각 입자에 대한`direction` 벡터와`velocity` 값을 저장 할 SO answer