개발/three.js / / 2022. 10. 20. 19:04

three.js 커스텀 오브젝트 생성 이벤트 만들기

반응형

Unity에서 Instantiate오 오브젝트를 생성하는 것처럼 커스텀 오브젝트를 three.js에서 생성하는 방법을 알아보자.

 

// CustomSphere.js

import { Body, Sphere, Vec3 } from 'cannon-es';
import { Mesh } from 'three';

export class CustomSphere{
    constructor(info){
        this.scene = info.scene;
        this.cannonWorld = info.cannonWorld;
        this.geometry = info.geometry;
        this.material = info.material;
        this.x = info.x;
        this.y = info.y;
        this.z = info.z;
        this.scale = info.scale;

        this.mesh = new Mesh(this.geometry, this.material);
        this.mesh.scale.set(this.scale, this.scale, this.scale);
        this.mesh.castShadow = true;
        this.mesh.position.set(this.x, this.y, this.z);
        this.scene.add(this.mesh);

        this.setCannonBody();
    }

    setCannonBody(){
        const shape = new Sphere(0.5 * this.scale);
        this.cannonBody = new Body({
            mass: 1,
            position: new Vec3(this.x, this.y, this.z),
            shape
        });

        this.cannonWorld.addBody(this.cannonBody);
    }
}

생성할 Object를 정의한 스크립트이다. 생성자에서 매개변수로 mesh를 추가할 scene, body를 적용할 world 등 다양한 요소들을 전달 받아온다. 

mesh 생성 및 여러 요소를 조정하고, body를 설정하는 함수를 생성자에서 실행한다.

 

// main.js
import { CustomSphere } from './CustomSphere';

...

// Mesh
const spheres = [];
const sphereGeometry = new THREE.SphereGeometry(0.5);
const sphereMaterial = new THREE.MeshStandardMaterial({
    color: 'seagreen'
});


// rendering
function draw() {
    const delta = clock.getDelta();

    let cannonStepTime = 1/60;
    if (delta < 0.01) cannonStepTime = 1/120;
    cannonWorld.step(cannonStepTime, delta, 3)

    spheres.forEach(item => {
        item.mesh.position.copy(item.cannonBody.position);
        item.mesh.quaternion.copy(item.cannonBody.quaternion);
    })

    renderer.render(scene, camera);
    renderer.setAnimationLoop(draw);
}

// event
canvas.addEventListener('click', () => {
    spheres.push(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
    }));
});

click event를 통해 CustomSphere를 생성하고, scene, world, geometry 등 각종 설정값들을 매개변수로 전달한다. 생성된 object는 spheres 배열에 담았다가 rendering시 각 프레임에서 body를 mesh에 적용시킨다.

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