https://editor.p5js.org/Yurriii/sketches/aKFTZSujn
Interactive Magnetic Field Simulation in p5.js
The Idea
I created an interactive particle system that simulates magnetic attraction. Particles respond to both gravity and a magnetic force controlled by the mouse. The magnet's strength increases when clicked, creating dynamic particle movements and colorful visual effects.
How It Works
The simulation uses:
- A particle system with physics (velocity, acceleration, mass)
- Inverse square law for magnetic force calculation
- Color changes based on particle speed
- Mouse interaction for magnetic control
Each particle responds to:
- Constant downward gravity
- Magnetic force when activated
- Bounce effects at canvas edges
- Drag to simulate air resistance
Interesting Challenges
The trickiest part was balancing the forces. Too much magnetic strength made particles fly everywhere, while too little made the interaction boring. I solved this by:
- Adding a drag coefficient (0.98) to dampen motion
- Constraining the magnetic force at very close distances
- Using particle mass to affect force response