
main.js
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const CUBE_COUNT = 500;
const SPACE_SIZE = 24;
const CUBE_SIZE = 0.8;
const MIN_SPEED = 0.05;
const MAX_SPEED = 0.35;
const SATURATION = 0.9;
const VALUE = 0.8;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x222831);
const camera = new THREE.PerspectiveCamera(
60,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.set(0, 0, SPACE_SIZE * 1.6);
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);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.minDistance = 2;
controls.maxDistance = 100;
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 };
}
const geometry = new THREE.BoxGeometry(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE);
const cubes = [];
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++) {
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);
}
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);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener('resize', onWindowResize);
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();
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);