İçeriğe geç
78 satır · 2,7 KBHamİndir
// Konfeti: tek InstancedMesh, parçacıklar yerçekimiyle düşüp dönerek süzülür.
import * as THREE from 'three';

const MAX = 1200;
const COLORS = [0xff3dbb, 0x3de8ff, 0xffd24a, 0x2ee59d, 0xb46bff, 0xffffff, 0xff6b4a].map((c) => new THREE.Color(c));

export function createConfetti(scene) {
  const mesh = new THREE.InstancedMesh(
    new THREE.PlaneGeometry(0.14, 0.09),
    new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, toneMapped: false }),
    MAX,
  );
  mesh.frustumCulled = false;
  mesh.count = 0;
  scene.add(mesh);
  const parts = [];
  const m = new THREE.Matrix4();
  const q = new THREE.Quaternion();
  const e = new THREE.Euler();
  const s = new THREE.Vector3(1, 1, 1);
  let cursor = 0;

  return {
    burst(origin, count = 100, spread = 3) {
      for (let i = 0; i < count; i++) {
        const p = {
          pos: origin.clone().add(new THREE.Vector3((Math.random() - 0.5) * spread, Math.random() * 1.5, (Math.random() - 0.5) * spread)),
          vel: new THREE.Vector3((Math.random() - 0.5) * 4, 2 + Math.random() * 5, (Math.random() - 0.5) * 4),
          rot: new THREE.Vector3(Math.random() * 6, Math.random() * 6, Math.random() * 6),
          spin: new THREE.Vector3(Math.random() * 8, Math.random() * 8, Math.random() * 8),
          life: 4 + Math.random() * 2,
        };
        const idx = parts.length < MAX ? parts.length : cursor++ % MAX;
        parts[idx] = p;
        mesh.setColorAt(idx, COLORS[(Math.random() * COLORS.length) | 0]);
      }
      if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
    },
    update(dt, t) {
      let n = 0;
      for (let i = 0; i < parts.length; i++) {
        const p = parts[i];
        if (!p) continue;
        p.life -= dt;
        if (p.life <= 0 || p.pos.y < 0.02) {
          if (p.life <= 0) {
            parts[i] = null;
            continue;
          }
          p.pos.y = 0.02;
          p.vel.set(0, 0, 0);
          p.spin.set(0, 0, 0);
        } else {
          p.vel.y -= 6 * dt;
          p.vel.multiplyScalar(1 - 1.8 * dt);
          p.vel.y = Math.max(p.vel.y, -1.4);
          p.pos.addScaledVector(p.vel, dt);
          p.pos.x += Math.sin(t * 3 + i) * dt * 0.4;
          p.rot.addScaledVector(p.spin, dt);
        }
        q.setFromEuler(e.set(p.rot.x, p.rot.y, p.rot.z));
        m.compose(p.pos, q, s);
        mesh.setMatrixAt(i, m);
        n = i + 1;
      }
      // boş yuvaları gizle
      for (let i = 0; i < n; i++) {
        if (!parts[i]) {
          m.makeScale(0, 0, 0);
          mesh.setMatrixAt(i, m);
        }
      }
      while (parts.length && !parts[parts.length - 1]) parts.pop();
      mesh.count = n;
      mesh.instanceMatrix.needsUpdate = true;
    },
  };
}

Lisans bilgisi projenin LICENSE dosyasında.