- Home /
How would you make an object behave like a magnet?
I have made a 2-d version of this by adding a CircleCollider2D to a empty object. Added a PointForceComponent script to the empty object, then adjusted its properties. For my initial test, I used the following values in the inspector:
Non Linear: True
Force: 5
Linear Drag: 0.1
Angular Drag: 0
The tracked Object is a simple circle sprite
But the only problem is that it only affects game objects that have the Rigid Body 2D and Collider 2D components. I would like to adapt this idea from 2D into 3D where by one object is positively charged and the other is negatively charged. Many Thanks. :)
This is simple enough to script, but it's not exactly clear what you're trying to achieve from the question. Do you just want 2 3D RigidBody objects to be attracted to each other, or do you want to properly simulate magnets with poles and attraction and repulsion?
Do you want to pull in all objects within a radius or do you just want interaction between 2 specific objects?
I was planning to 'properly simulate magnets with poles and attraction and repulsion'. So like one magnet is (+) and the other is (-).
Well that isn't how magnets actually work. $$anonymous$$agnets all have both a North and South pole. Would you want to simulate this?
Just an idea! I think you need a "GravityAttractor" script on your object and have a "GravityBody" script on your player, then your player will get attracted to the object maybe?:)
Even if magnets do not work like that. Would there be some way to have one object (+) and an other (-).
Answer by Fattie · Aug 15, 2015 at 12:43 PM
Assuming you want object B to always be attracted to object A.
Simply, add a script to B. Have with one line of code which causes B to feel force in the direction towards A.
The strength of the magnetic field is (ROUGHLY) 1 divided by the distance between the two squared.
Good luck.
To increase the general frisson of your ongoing quest for knowledge,
• learn that the direction from A to B is (B-A)
• find the Vector2 or Vector3 documentation, look for "distance" related functions
• learn about normalizing a vector to length one, the purpose and mechanisms of this
• learn how to apply force to an object, the subtleties of doing so each frame
Enjoy!
Thank you Fattie. Even though I understand what you mean, the only problem is that I would not know how to create 'one line of code which causes B to feel force in the direction towards A' in a 3-D format.
You're welcome, thanks for the thanks. I've added some more info to help on your quest.
ok, I get that. That should help me understand what I need to do. Really helpful. thank you.