개발/three.js / / 2022. 10. 24. 13:22

three.js collision과 sound 적용해보기

반응형

이벤트로 생성한 custom sphere가 충돌하였을 때 충돌 콜백함수로 sound를 재생하는 방법을 알아보자.

 

// sound when collision
const sound = new Audio('/sounds/boing.mp3');

function collide(e) {
    const velocity = e.contact.getImpactVelocityAlongNormal();
    if(velocity > 3){
        sound.currentTime = 0;
        sound.play();
    }
}

// event
canvas.addEventListener('click', () => {
    const customSphere = new CustomSphere({
        // scene: scene,
        scene,
        cannonWorld,
        geometry: sphereGeometry,
        material: sphereMaterial,
        x: (Math.random() - 0.5) * 2,
        y: Math.random() * 5 + 2,
        z: (Math.random() - 0.5) * 2,
        scale: Math.random() + 0.2
    });

    spheres.push(customSphere);

    customSphere.cannonBody.addEventListener('collide', collide);
});

Audio객체를 이용해서 sound object를 생성하고 play()로 실행할 수 있다. 

 

collide함수를 addEventListener를 통해 customSphere의 body의 'collide'함수의 이벤트로 설정하면 collide함수 이벤트가 충돌시 실행된다.

collide함수의 매개변수인 e는 충돌했을 때 충돌정보를 가져올 수 있다. 이 충돌 정보에서 충돌했을 때 속력을 통해 일정 속력 이상으로 충돌하면 sound가 재생하게 할 수 있다.

 

sound를 재생할 때 하나의 사운드가 이미 실행 중이라면 같은 Audio객체에서는 동시에 여러 sound를 재생할 수 없기 때문에 currentTime을 0으로 설정하는 것으로 재생 중인 sound의 시간을 0으로 초기화하여 다시 재생하는 방법을 사용한다.

 

실제로 Unity에서 sound를 다룰 때에는 각 sound마다 개별 component를 사용하여 동시에 여러 사운드가 재생하는 방법을 사용하기에 three.js에서도 같은 방식으로 구성할 수 있을 것이다.

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