Class-02-Random-Cubes

BamgasiJM·2026년 11월 9일

Three.js

목록 보기
11/22
post-thumbnail

main.js

// ============================================================
// 1. Three.js 모듈 불러오기
//    index.html의 importmap에 'three'와 'three/addons/'가 등록되어 있어야 합니다.
// ============================================================
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

// ============================================================
// 2. 설정값
// ============================================================
const CUBE_COUNT = 500;
const SPACE_SIZE = 24;        // 큐브가 떠 있는 정육면체 공간의 한 변 길이
const CUBE_SIZE = 0.8;        // 큐브 한 변 길이
const MIN_SPEED = 0.05;       // 회전 속도 최솟값 (rad/s)
const MAX_SPEED = 0.35;       // 회전 속도 최댓값 (rad/s)
const SATURATION = 0.9;       // HSV S = 90
const VALUE = 0.8;            // HSV V = 80

// ============================================================
// 3. 씬(Scene) 생성
// ============================================================
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x222831);

// ============================================================
// 4. 카메라(PerspectiveCamera) 설정
// ============================================================
const camera = new THREE.PerspectiveCamera(
  60,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
camera.position.set(0, 0, SPACE_SIZE * 1.6);

// ============================================================
// 5. 렌더러(WebGLRenderer) 설정
// ============================================================
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// ============================================================
// 6. OrbitControls 설정
//    마우스 드래그: 회전 / 휠: 줌 / 우클릭 드래그: 이동
// ============================================================
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;   // 관성 효과 (매 프레임 update() 필요)
controls.dampingFactor = 0.05;
controls.minDistance = 2;
controls.maxDistance = 100;

// ============================================================
// 7. HSV → HSL 변환
//    Three.js Color는 HSL만 지원하므로 HSV 값을 변환합니다.
//    l = v * (1 - s / 2),  s_l = (v - l) / min(l, 1 - l)
// ============================================================
function hsvToHsl(h, s, v) {
  const l = v * (1 - s / 2);
  const sl = (l === 0 || l === 1) ? 0 : (v - l) / Math.min(l, 1 - l);
  return { h, s: sl, l };
}

// ============================================================
// 8. 큐브 500개 생성
//    지오메트리는 공유하고, 색이 다르므로 머티리얼은 개별 생성합니다.
// ============================================================
const geometry = new THREE.BoxGeometry(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE);
const cubes = [];

// 회전 속도: 크기는 MIN~MAX 사이 랜덤, 방향(부호)도 랜덤
function randomSpeed() {
  const speed = THREE.MathUtils.randFloat(MIN_SPEED, MAX_SPEED);
  return Math.random() < 0.5 ? -speed : speed;
}

for (let i = 0; i < CUBE_COUNT; i++) {
  // 색상: H만 랜덤, S/V 고정
  const hsl = hsvToHsl(Math.random(), SATURATION, VALUE);
  const material = new THREE.MeshStandardMaterial({
    roughness: 0.4,
    metalness: 0.1,
  });
  material.color.setHSL(hsl.h, hsl.s, hsl.l);

  const cube = new THREE.Mesh(geometry, material);

  // 위치: 공간 안에서 랜덤
  cube.position.set(
    THREE.MathUtils.randFloatSpread(SPACE_SIZE),
    THREE.MathUtils.randFloatSpread(SPACE_SIZE),
    THREE.MathUtils.randFloatSpread(SPACE_SIZE)
  );

  // 초기 회전: 랜덤
  cube.rotation.set(
    Math.random() * Math.PI * 2,
    Math.random() * Math.PI * 2,
    Math.random() * Math.PI * 2
  );

  // 축별 회전 속도 저장
  cube.userData.spin = new THREE.Vector3(randomSpeed(), randomSpeed(), randomSpeed());

  scene.add(cube);
  cubes.push(cube);
}

// ============================================================
// 9. 조명 설정
// ============================================================
const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(ambientLight);

const directionalLight = new THREE.DirectionalLight(0xffffff, 2);
directionalLight.position.set(3, 4, 5);
scene.add(directionalLight);

// ============================================================
// 10. 창 크기 변경 대응
// ============================================================
function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener('resize', onWindowResize);

// ============================================================
// 11. 애니메이션 루프
//     Timer의 delta 값을 사용해 프레임레이트와 무관하게 같은 속도로 회전합니다.
// ============================================================
const timer = new THREE.Timer();

function animate(timestamp) {
  timer.update(timestamp);
  const delta = timer.getDelta();

  for (const cube of cubes) {
    const spin = cube.userData.spin;
    cube.rotation.x += spin.x * delta;
    cube.rotation.y += spin.y * delta;
    cube.rotation.z += spin.z * delta;
  }

  controls.update(); // damping 적용에 필요
  renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);

profile
Coding Art with Blender / Three.js / p5.js / GLSL Shader / Processing / nannou

0개의 댓글