개발/three.js / / 2022. 10. 27. 13:04

three.js particle 랜덤으로 생성하기

반응형

Unity의 particle을 아는가 그것과 같은 의미이다. 생소한 개념이 나올 수 있다. 주의하자.

 

// Mesh
const geometry = new THREE.SphereGeometry(1, 32, 32);
const material = new THREE.PointsMaterial({
    size: 0.02,
    sizeAttenuation: false
});
const points = new THREE.Points(geometry, material);
scene.add(points);

particle을 생성하기 위해서 material로 PointsMaterial을 사용하였다. 이를 사용하면 아래처럼 점으로 구성된 원을 볼 수 있다.

PointsMaterial의 size값으로 각 점의 크기를 설정할 수 있고, sizeAttenuation값을 false로 설정함으로써 카메라의 원근과 상관없이 같은 크기로 고정할 수 있다.

 

 

// Points
const geometry = new THREE.BufferGeometry();
const count = 100000;
const positions = new Float32Array(count * 3);
for(let i = 0; i < positions.length; i++){
    positions[i] = (Math.random() - 0.5) * 10;
}
geometry.setAttribute(
    'position', 
    new THREE.BufferAttribute(positions, 3)
);
const material = new THREE.PointsMaterial({
    size: 0.03,
    color: 'gold',
});
const particles = new THREE.Points(geometry, material);
scene.add(particles);

이번에는 각 랜덤 포지션에 point를 찍어내는 랜덤 파티클 코드이다.

 

여기서는 geometry의 형태가 정해져있지 않으므로, BufferGeometry를 사용한다.

gl 프로그래밍에서 흔히 볼 수 있었던 BufferGeometry는 geometry의 vertex를 직접 지정해주는 것이다. 

 

BufferGeometry의 경우 각 vertex의 position array를 직접 설정해주어야 한다.

따라서 Float32Array를 통해 count개수만클 position array를 생성하고, position array를 geometry의 'position' attribute로 setting하는 작업이 필요하다.

 

setting할 때 position array를 BufferAttribute객체로 생성해서 매개변수로 전달해야하는데, vertex를 설정할 때 vertex 하나 당 값 3개가 필요하기 때문에 매개변수로 3을 전달한다. 이런 구조를 보면 마치 openGL을 보는 것 같다.

 

참고로 Math.random은 0~1사이의 범위이므로 0.5를 뺌으로써 -0.5~0.5의 범위로 설정한다. 

 

생성한 geometry와 material을 Points 객체로 생성해서 scene에 추가해보자.

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유