Okay, this is a fun one! We'll create a single HTML file with Three.js to visualize particles attracting each other. I'll use a simple Newtonian gravity-like model where every particle attracts every other particle, but with some damping to prevent them from just clumping instantly.
Here's the complete index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three.js Particle Attraction</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<!-- Three.js Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.165.0/three.min.js"></script>
<!-- OrbitControls for camera interaction -->
<script src="https://unpkg.com/three@0.165.0/examples/jsm/controls/OrbitControls.js"></script>
<script>
// --- Configuration Constants ---
const NUM_PARTICLES = 200; // Number of particles (be careful increasing too much, O(N^2) complexity)
const SIMULATION_RADIUS = 200; // Initial spread radius for particles
const ATTRACTION_STRENGTH = 0.5; // How strong the attraction is
const DAMPING_FACTOR = 0.99; // Reduces velocity each frame (simulates air resistance/friction)
const MIN_DISTANCE_SQR = 100; // Minimum squared distance to prevent extreme forces when particles are very close
const PARTICLE_SIZE = 1.5; // Visual size of each particle
// --- Three.js Setup ---
let scene, camera, renderer, controls;
let particles; // THREE.Points object
let positions; // Float32Array for particle positions
let colors; // Float32Array for particle colors
let particleData = []; // Array to hold { position: Vector3, velocity: Vector3, color: Color } for physics
init();
animate();
function init() {
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x050505); // Dark background
// Camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 300; // Pull camera back to see the particles
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// OrbitControls for interactive camera
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // Smooth camera movement
controls.dampingFactor = 0.05;
// --- Particle System Creation ---
const geometry = new THREE.BufferGeometry();
positions = new Float32Array(NUM_PARTICLES * 3); // x, y, z for each particle
colors = new Float32Array(NUM_PARTICLES * 3); // r, g, b for each particle
const tempColor = new THREE.Color();
for (let i = 0; i < NUM_PARTICLES; i++) {
const i3 = i * 3;
// Initial position: randomly distributed within a sphere
const x = (Math.random() - 0.5) * 2 * SIMULATION_RADIUS;
const y = (Math.random() - 0.5) * 2 * SIMULATION_RADIUS;
const z = (Math.random() - 0.5) * 2 * SIMULATION_RADIUS;
positions[i3] = x;
positions[i3 + 1] = y;
positions[i3 + 2] = z;
// Random initial velocity (can be zero for static start, or small random for subtle movement)
const velocity = new THREE.Vector3(
(Math.random() - 0.5) * 0.1,
(Math.random() - 0.5) * 0.1,
(Math.random() - 0.5) * 0.1
);
// Assign a random color to each particle
tempColor.setHSL(Math.random(), 0.7, 0.5); // Hue, Saturation, Lightness
colors[i3] = tempColor.r;
colors[i3 + 1] = tempColor.g;
colors[i3 + 2] = tempColor.b;
particleData.push({
position: new THREE.Vector3(x, y, z),
velocity: velocity,
color: tempColor.clone() // Store original color for potential later use
});
}
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
// Material for particles
const material = new THREE.PointsMaterial({
size: PARTICLE_SIZE,
vertexColors: true, // Use colors from the geometry attribute
transparent: true,
blending: THREE.AdditiveBlending, // For a glowing, ethereal look
sizeAttenuation: true // Particles closer to camera appear larger
});
// Create the Points object and add to scene
particles = new THREE.Points(geometry, material);
scene.add(particles);
// Handle window resizing
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// --- Animation Loop ---
function animate() {
requestAnimationFrame(animate);
updateParticles(); // Update particle physics
controls.update(); // Update OrbitControls
renderer.render(scene, camera);
}
// --- Particle Physics Update ---
function updateParticles() {
const numParticles = particleData.length;
// Loop through each particle to calculate forces
for (let i = 0; i < numParticles; i++) {
const p1 = particleData[i];
let totalForce = new THREE.Vector3();
// Loop through all other particles to calculate attraction
for (let j = 0; j < numParticles; j++) {
if (i === j) continue; // Don't attract to self
const p2 = particleData[j];
// Vector from p1 to p2
const direction = new THREE.Vector3().subVectors(p2.position, p1.position);
let distanceSq = direction.lengthSq(); // Squared distance
// Add a small constant to distanceSq to prevent division by zero or extreme forces
// when particles are very close.
distanceSq = Math.max(distanceSq, MIN_DISTANCE_SQR);
const forceMagnitude = ATTRACTION_STRENGTH / distanceSq; // Inverse square law for attraction
direction.normalize().multiplyScalar(forceMagnitude);
totalForce.add(direction);
}
// Apply total force to velocity
p1.velocity.add(totalForce);
// Apply damping (friction)
p1.velocity.multiplyScalar(DAMPING_FACTOR);
// Update position
p1.position.add(p1.velocity);
// Update the BufferGeometry's position array
const i3 = i * 3;
positions[i3] = p1.position.x;
positions[i3 + 1] = p1.position.y;
positions[i3 + 2] = p1.position.z;
}
// Tell Three.js that the position attribute needs to be updated on the GPU
particles.geometry.attributes.position.needsUpdate = true;
}
</script>
</body>
</html>