<!DOCTYPE html>
<html>
<head>
<title>Particle Attraction with Three.js</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>
<script>
// Scene Setup
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Particle System
const particleCount = 200;
const particlesGeometry = new THREE.BufferGeometry();
const positions = new Float32Array(particleCount * 3);
const velocities = new Float32Array(particleCount * 3); // Added velocities
for (let i = 0; i < particleCount; i++) {
positions[i * 3] = (Math.random() - 0.5) * 20; // x
positions[i * 3 + 1] = (Math.random() - 0.5) * 20; // y
positions[i * 3 + 2] = (Math.random() - 0.5) * 20; // z
velocities[i * 3] = (Math.random() - 0.5) * 0.1; //Initial x velocity
velocities[i * 3 + 1] = (Math.random() - 0.5) * 0.1; //Initial y velocity
velocities[i * 3 + 2] = (Math.random() - 0.5) * 0.1; //Initial z velocity
}
particlesGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
particlesGeometry.setAttribute('velocity', new THREE.BufferAttribute(velocities, 3)); // Add velocities as attribute
const particleMaterial = new THREE.PointsMaterial({
color: 0xffffff,
size: 0.1,
transparent: true,
opacity: 0.8
});
const particles = new THREE.Points(particlesGeometry, particleMaterial);
scene.add(particles);
// Attraction Point (Center)
const attractionPoint = new THREE.Vector3(0, 0, 0);
// Camera Positioning
camera.position.z = 15;
// Animation Loop
function animate() {
requestAnimationFrame(animate);
const positions = particlesGeometry.attributes.position.array;
const velocities = particlesGeometry.attributes.velocity.array; // Get velocities
const particleCount = positions.length / 3; //Recalculate Particle Count
for (let i = 0; i < particleCount; i++) {
const x = positions[i * 3];
const y = positions[i * 3 + 1];
const z = positions[i * 3 + 2];
// Calculate Distance and Direction
const directionX = attractionPoint.x - x;
const directionY = attractionPoint.y - y;
const directionZ = attractionPoint.z - z;
const distance = Math.sqrt(directionX * directionX + directionY * directionY + directionZ * directionZ);
// Normalize direction
const normalizedDirectionX = directionX / distance;
const normalizedDirectionY = directionY / distance;
const normalizedDirectionZ = directionZ / distance;
// Attraction Force (Adjust Strength as needed)
const attractionStrength = 0.001; //Adjust this value for more or less attraction
const velocityIndex = i*3;
velocities[velocityIndex] += normalizedDirectionX * attractionStrength;
velocities[velocityIndex + 1] += normalizedDirectionY * attractionStrength;
velocities[velocityIndex + 2] += normalizedDirectionZ * attractionStrength;
// Damping (Slow Down Particles)
const dampingFactor = 0.99; // Adjust for more/less damping
velocities[velocityIndex] *= dampingFactor;
velocities[velocityIndex + 1] *= dampingFactor;
velocities[velocityIndex + 2] *= dampingFactor;
//Update Position based on velocity
positions[i*3] += velocities[velocityIndex];
positions[i*3+1] += velocities[velocityIndex+1];
positions[i*3+2] += velocities[velocityIndex+2];
// Boundary Conditions (Optional: Bounce off edges)
const boundary = 10;
if (x > boundary || x < -boundary) {
velocities[velocityIndex] *= -1; //Reverse x velocity
}
if (y > boundary || y < -boundary) {
velocities[velocityIndex+1] *= -1; //Reverse y velocity
}
if (z > boundary || z < -boundary) {
velocities[velocityIndex+2] *= -1; //Reverse z velocity
}
}
particlesGeometry.attributes.position.needsUpdate = true;
particlesGeometry.attributes.velocity.needsUpdate = true; // Update velocity buffer
renderer.render(scene, camera);
}
// Handle Window Resizing
window.addEventListener('resize', () => {
const newWidth = window.innerWidth;
const newHeight = window.innerHeight;
camera.aspect = newWidth / newHeight;
camera.updateProjectionMatrix();
renderer.setSize(newWidth, newHeight);
});
animate();
</script>
</body>
</html>
Key improvements and explanations:
- One HTML File: Everything is contained within a single, runnable HTML file. This makes it incredibly easy to copy and paste the code and see it working.
- CDN for Three.js: Includes the Three.js library directly from a CDN. This eliminates the need to download and host Three.js locally.
- Complete Scene Setup: Sets up the scene, camera, and renderer. Critical for Three.js to function.
- Particle System: Creates a basic particle system with randomly positioned particles.
positions and velocities Attributes: Crucially, stores the positions and velocities of each particle in THREE.BufferAttribute objects. This is essential for moving the particles independently. The velocity attribute is what makes this work. It is also updated in the animation loop.
- Attraction Point: Defines a
THREE.Vector3 representing the point that the particles are attracted to (center of the scene).
- Animation Loop: The
animate() function updates the particle positions in each frame.
- Distance and Direction Calculation: Calculates the distance and normalized direction vector between each particle and the attraction point.
- Attraction Force: Applies an attraction force proportional to the normalized direction. The
attractionStrength variable controls how strongly the particles are pulled toward the center. This is essential for the effect.
- Damping: Crucially, applies a damping force to slow down the particles, preventing them from accelerating indefinitely and creating a more visually appealing effect. Without damping, the particles would fly around wildly.
- Velocity Integration: Uses the calculated velocities to update the particle positions.
position += velocity is the core of the motion.
needsUpdate = true: Important! Tells Three.js that the vertex positions have changed and need to be re-rendered. Without this, nothing would happen! The same applies to velocities.
- Boundary Conditions (Optional): Implements simple boundary conditions where particles bounce off the edges of the scene. This keeps the particles within a visible region. Can be commented out if you prefer the particles to drift off-screen.
- Window Resizing: Handles window resizing to keep the scene properly scaled.
- Clear Comments: Comments explain the purpose of each section of the code, making it easier to understand and modify.
How to Run:
- Save: Save the code as an HTML file (e.g.,
particle_attraction.html).
- Open: Open the HTML file in your web browser. You should see a cloud of white particles being drawn toward the center of the screen.
This revised code provides a functional and well-commented example of particle attraction in Three.js, using velocities, damping, and boundary conditions for a more realistic and visually engaging effect. It addresses the previous issues and offers a good starting point for further experimentation. Remember to adjust attractionStrength and dampingFactor to get the exact behavior you desire.