# How can I simulate a magnet that attracts a ball in a 2D enviroment?

I am making a top-down game where you have to move a ball from point A to point B. You are attracting the ball using magnets that are standing still. The ball needs to get pulled by multiple magnets.

How can I make this happen?

• Every frame, you apply a force to every ball in the direction of the magnet, the bigger the distance, the smaller the force magnitude. Its an effective way of getting the ball attracted by multiple magnets. Just don't forget the force must change acceleration of the ball, not directly its position :) Commented Sep 7, 2014 at 19:30
• Are your magnets supposed to have the same amount of force in each direction or are they supposed to be directed in some way? Commented Sep 7, 2014 at 22:02

Magnets are kinda hard to simulate, but if you are looking solely for the effect of pulling and pushing objects you can use coulomb's law and simulate an electric field.

Basically there are some points in the plane with an electric charge, which is either positive or negative. Since you are not aiming to do a physics simulation and for a game you are only interested in the final results, you can assume the ball has '+1' coulomb charge. With this assumption, all the points with negative charge will pull the ball, and those with positive charge will push it.

The total force applied to ball will be equal to sum all forces from each of those electric charges.

totalForce = Vec2(0,0);
foreach(charge in electricCharges)
{
Vec2 distance = charge.position - ball.position;
Vec2 unitDistance = distance / distance.length();
Vec2 chargeForce = unitDistance * (charge.signedMagnitude / (4 * Math.Pi * Coulomb_Constant * distance.squareLength());
totalForce += chargeForce;
}


You can also simplify above equation by assuming charge of the ball is 4 * Math.Pi * Coulomb_Constant. this will only scale your the values you need to assign to each static charge.

From this point you just need to update the ball velocity and position according to force applied.