This is a simple particle simulation where:
The canvas is fetched and its size is set based on the width of the container. The number of particles, their radius, and speed are set. An array for positions and velocities of the particles is created.
initializeParticles
function:
This function initializes the positions of the particles randomly within the canvas, making sure they
are not too close to the boundaries. The velocities of the particles are set randomly based on the
SPEED
.
updateParticles
function:This function updates the position and velocities of the particles. Boundary collisions are detected, and the velocity is reversed if a particle hits the boundary. Particle-particle collisions are detected and velocities are updated accordingly. A rotation matrix is applied to simplify the calculation of the collision in 1D, and then it's converted back to 2D.
drawParticles
function:Clears the canvas and then draws each particle at its current position.
mainLoop
function:
This is the main animation loop. It calls updateParticles
to update positions and
velocities and then calls drawParticles
to render the particles on the canvas. The
requestAnimationFrame
method is used to call the mainLoop
function again,
creating an animation.
restartSimulation
and updateNumParticles
functions:restartSimulation
: Resets the simulation.updateNumParticles
: Updates the number of particles based on user input and
reinitializes the simulation.Whenever the window is resized, the size of the canvas is updated, and the particles are reinitialized.
Finally, the particles are initialized and the animation loop starts with the call to
mainLoop
.
This is a neat simulation that showcases the basics of particle physics in a confined space with simple elastic collisions.