Here's a self-contained HTML file with a 2D verlet particle simulation that meets your requirements. The simulation uses spatial hashing for efficient collision detection and includes mouse interaction:
<!DOCTYPE html>
<html>
<head>
<title>Verlet Particle Simulation</title>
<style>
canvas {
border: 1px solid black;
}
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Set canvas to window size
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
class Particle {
constructor(x, y) {
this.currentX = x;
this.currentY = y;
this.oldX = x;
this.oldY = y;
this.radius = 3;
this.mass = 1;
}
update(dt) {
const velocityX = (this.currentX - this.oldX);
const velocityY = (this.currentY - this.oldY);
// Save current position
this.oldX = this.currentX;
this.oldY = this.currentY;
// Apply velocity and gravity
this.currentX += velocityX;
this.currentY += velocityY + 0.5; // gravity
// Boundary constraints
if (this.currentX < this.radius) {
this.currentX = this.radius;
this.oldX = this.currentX + velocityX * 0.5;
}
if (this.currentX > canvas.width - this.radius) {
this.currentX = canvas.width - this.radius;
this.oldX = this.currentX + velocityX * 0.5;
}
if (this.currentY < this.radius) {
this.currentY = this.radius;
this.oldY = this.currentY + velocityY * 0.5;
}
if (this.currentY > canvas.height - this.radius) {
this.currentY = canvas.height - this.radius;
this.oldY = this.currentY + velocityY * 0.5;
}
}
draw() {
ctx.beginPath();
ctx.arc(this.currentX, this.currentY, this.radius, 0, Math.PI * 2);
ctx.fillStyle = 'black';
ctx.fill();
}
}
class SpatialHash {
constructor(cellSize) {
this.cellSize = cellSize;
this.grid = new Map();
}
clear() {
this.grid.clear();
}
hash(x, y) {
return `${Math.floor(x / this.cellSize)},${Math.floor(y / this.cellSize)}`;
}
insert(particle) {
const key = this.hash(particle.currentX, particle.currentY);
if (!this.grid.has(key)) {
this.grid.set(key, []);
}
this.grid.get(key).push(particle);
}
queryNearby(x, y) {
const key = this.hash(x, y);
const nearby = [];
// Check 9 neighboring cells
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
const neighborKey = this.hash(
x + i * this.cellSize,
y + j * this.cellSize
);
if (this.grid.has(neighborKey)) {
nearby.push(...this.grid.get(neighborKey));
}
}
}
return nearby;
}
}
class Simulation {
constructor() {
this.particles = [];
this.spatialHash = new SpatialHash(10);
this.mouse = { x: 0, y: 0, radius: 20 };
// Add initial particles
for (let i = 0; i < 100; i++) {
this.particles.push(new Particle(
Math.random() * canvas.width,
Math.random() * canvas.height
));
}
// Mouse events
canvas.addEventListener('mousemove', (e) => {
this.mouse.x = e.clientX;
this.mouse.y = e.clientY;
});
canvas.addEventListener('click', () => {
for (let i = 0; i < 10; i++) {
this.particles.push(new Particle(
this.mouse.x + (Math.random() - 0.5) * 20,
this.mouse.y + (Math.random() - 0.5) * 20
));
}
});
}
solveCollisions() {
this.spatialHash.clear();
for (const particle of this.particles) {
this.spatialHash.insert(particle);
}
// Mouse collision
for (const particle of this.particles) {
const dx = particle.currentX - this.mouse.x;
const dy = particle.currentY - this.mouse.y;
const dist = Math.sqrt(dx * dx + dy * dy);
const minDist = particle.radius + this.mouse.radius;
if (dist < minDist) {
const angle = Math.atan2(dy, dx);
const targetX = this.mouse.x + Math.cos(angle) * minDist;
const targetY = this.mouse.y + Math.sin(angle) * minDist;
const ax = (targetX - particle.currentX) * 0.5;
const ay = (targetY - particle.currentY) * 0.5;
particle.currentX = targetX;
particle.currentY = targetY;
particle.oldX = particle.currentX - ax;
particle.oldY = particle.currentY - ay;
}
}
// Particle-particle collision
for (const particle of this.particles) {
const nearby = this.spatialHash.queryNearby(particle.currentX, particle.currentY);
for (const other of nearby) {
if (particle === other) continue;
const dx = other.currentX - particle.currentX;
const dy = other.currentY - particle.currentY;
const dist = Math.sqrt(dx * dx + dy * dy);
const minDist = particle.radius + other.radius;
if (dist < minDist) {
const angle = Math.atan2(dy, dx);
const targetX = particle.currentX + Math.cos(angle) * minDist;
const targetY = particle.currentY + Math.sin(angle) * minDist;
const ax = (targetX - other.currentX) * 0.5;
const ay = (targetY - other.currentY) * 0.5;
other.currentX = targetX;
other.currentY = targetY;
particle.currentX = particle.currentX - ax;
particle.currentY = particle.currentY - ay;
}
}
}
}
update() {
for (const particle of this.particles) {
particle.update(1/60);
}
this.solveCollisions();
}
draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw mouse circle
ctx.beginPath();
ctx.arc(this.mouse.x, this.mouse.y, this.mouse.radius, 0, Math.PI * 2);
ctx.strokeStyle = 'rgba(0, 0, 0, 0.2)';
ctx.stroke();
// Draw particles
for (const particle of this.particles) {
particle.draw();
}
}
}
const simulation = new Simulation();
function animate() {
simulation.update();
simulation.draw();
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
This simulation features:
- Verlet integration for stable physics
- Spatial hashing for efficient collision detection
- Accurate particle-particle and particle-mouse collisions
- Natural gravity
- Mouse interaction (collision and particle spawning)
- Responsive canvas that fills the window
To use it, just save it as an HTML file and open it in a browser. Click anywhere to spawn 10 new particles, and move your mouse to interact with the particles. The particles will collide with each other, the mouse, and the screen boundaries while being affected by gravity.
The simulation uses spatial hashing to make collision detection more efficient, which allows it to handle hundreds of particles smoothly. The verlet integration method provides stable physics without explicit velocity calculations, and the collision response is designed to prevent particle explosions or unstable behavior.