How to simulate a magnet?

Discuss any questions about BEPUphysics or problems encountered.
Post Reply
JHOW
Posts: 9
Joined: Mon Oct 26, 2009 12:52 am

How to simulate a magnet?

Post by JHOW »

I am making a game which requires magnets. I have magnetic refrigerator letters that need to stick to the refrigerator door. They also need to break away if you pull them far enough away from the door, and also reattach when they get close enough. Any ideas?

These are what i am talking about.
Image
Norbo
Site Admin
Posts: 4929
Joined: Tue Jul 04, 2006 4:45 am

Re: How to simulate a magnet?

Post by Norbo »

If the surface is pretty simple (like a fridge, which is basically a flat plane), you could do something resembling 'physical' magnetism.

For any magnets that are close enough to be attracted to the fridge, you can apply a simple linear force. Something like,

Code: Select all

magnet.applyLinearImpulse(fridgeSurfaceNormal * (-magnetStrengthConstant / (distance * distance)));
In this example, you'd want to keep distance away from zero to avoid singularities and infinite force. You could arbitrarily add a little buffer to the distance so it feels right.

With a sufficiently high 'magnetism strength constant' and fridge/magnet friction, the magnet will stick to the fridge, even with gravity pulling it down.

If you wanted a little more accuracy, you could simulate multiple submagnets attached to each magnet. An impulse would be computed at each point and applied using magnet.applyImpulse. This is like numerically integrating the 'magnetic' force across the magnet's surface. This would also give you more power to determine which parts of the magnet entity are actually magnetic. For example, most fridge magnets have a little strip on the back and the rest is plastic. Putting it plastic-first on a fridge will result it in falling off since the magnet is too far from the surface.

To avoid tiny drift due to gravity, it's a good idea to let objects go to sleep. That means avoiding some of the overloads of the applyImpulse method that automatically wake entities up. Later, if a user manipulates the magnet by applying impulses, you would need to remember to force the entity awake.
Post Reply