- Home /
How to make a N-S magnet Javascript?
Hello, im new to scripting as many otheres. Ive been trying to come up with a script that will allow me to just have an object with one half a "north" feild and the other with a "south" field. If the script then applyed to a secound objet, both will react like regular magnets. N/n or S/s will push them away from them selfs and if N/S then just pull together. Its for a puzzel game that ive been working on. Thank you for spending the time on reading my question and any help in anyway is greatly welcomed.
Answer by Fattie · Nov 11, 2012 at 09:54 AM
Hi, will you have JUST THE TWO magnets, or many?
Please state exactly how many you will have.
Quite simply, you would make a script that uses FixedUpdate to "AddForce" to the object each time.
Specifically, you will need to use "Rigidbody.AddForceAtPosition"
http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody.AddForceAtPosition.html
On the object, make two "markers" (empty objects) to show the exact positions of the N and S pole (ie, in fact the center of the end of the rectangle). those are the "position" at which you will AddForceAtPosition.
write one script for the north poles, and one script for the south poles.
quite simply, you will have to LOOK AROUND for any poles, and then add a force towards that one.
So, you will have a List, we'll cal it AllNorthPoles. You must maintain this list with all the north poles in the game. (So when you add a new magnet, put the north pole in AllNorthPoles and the south pole in AllSouthPoles.)
in your script for a south pole, just do this:
for all of the AllNorthPoles
use AddForceAtPosition to make a force towards that north pole
so it's that easy. PhysX will do the rest, and they will move around magically.
if you do not actually know the physics formula for the force applied by a magnet over distance, that is not so good! As a first step, carefully study magnets on Wikipedia.
Beyond this if you need any SPECIFIC questions (like "how to use List") ask a new specific question. Also go to unityGEMS.com for a great beginner intro to many topics.
be sure to TICK any useful answers, it is the round tick symbol under the thumbs. only you can close out your own questions and keep the board tidy.
As a test and to get a feel for the correct numbers, try with a ball and just a North pole: each frame just `AddForce(dir * F*1/d-squared)`. Shooting a marble should give an "asteroid past a planet" look. Then maybe flip to repel, using negative dir. $$anonymous$$aybe try using both at once. Then add the lists.
Your answer
Follow this Question
Related Questions
How to make a N-S Magnet Javascrip? 0 Answers
Convert this line of javascript to C# (easy) 1 Answer
player prefs, problem but no problem??? 1 Answer
get closest enemy 1 Answer
Bug/Error in script CollectPapers 0 Answers