Sure! Here's an implementation of a basic particle collision algorithm in JavaScript using the HTML Canvas:
html
<!DOCTYPE html>
<html>
<head>
<title>Particle Collision Simulation</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Define the canvas size
canvas.width = window.innerWidth - 20;
canvas.height = window.innerHeight - 20;
// Define the particle class
class Particle {
constructor(x, y, radius, dx, dy, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.dx = dx;
this.dy = dy;
this.color = color;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
update() {
if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
this.dx = -this.dx;
}
if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
this.dy = -this.dy;
}
this.x += this.dx;
this.y += this.dy;
this.draw();
}
collisionCheck(particles) {
for (let i = 0; i < particles.length; i++) {
if (this === particles[i]) continue;
const distance = Math.sqrt(
Math.pow(this.x - particles[i].x, 2) +
Math.pow(this.y - particles[i].y, 2)
);
if (distance <= this.radius + particles[i].radius) {
// collision detected
const angle = Math.atan2(
particles[i].y - this.y,
particles[i].x - this.x
);
const velocity1 = Math.sqrt(
Math.pow(this.dx, 2) +
Math.pow(this.dy, 2)
);
const velocity2 = Math.sqrt(
Math.pow(particles[i].dx, 2) +
Math.pow(particles[i].dy, 2)
);
const direction1 = Math.atan2(this.dy, this.dx);
const direction2 = Math.atan2(particles[i].dy, particles[i].dx);
const newVelocity1 = velocity2 * Math.cos(direction2 - angle);
const newVelocity2 = velocity1 * Math.cos(direction1 - angle);
const finalVelocity1 = ((this.radius - particles[i].radius) * velocity1 +
(2 * particles[i].radius) * velocity2) / (this.radius + particles[i].radius);
const finalVelocity2 = ((particles[i].radius - this.radius) * velocity2 +
(2 * this.radius) * velocity1) / (this.radius + particles[i].radius);
const newDX1 = newVelocity1 * Math.cos(angle) +
velocity1 * Math.sin(direction1 - angle) * Math.cos(angle + Math.PI / 2);
const newDY1 = newVelocity1 * Math.sin(angle) +
velocity1 * Math.sin(direction1 - angle) * Math.sin(angle + Math.PI / 2);
const newDX2 = newVelocity