- Home /
Objects acting under each other's gravity. Test
I want to test the revised script from http://answers.unity3d.com/questions/196749/objects-acting-under-each-others-gravity.html (script from the best answer). I've completed the script, but it doesn't work:
#pragma strict
var planet : Transform;
var numberOfPlanets = 10;
var minimumSize = 1;
var maximumSize = 10;
var position = Vector3.zero;
var planets = new Array ();
var masses = new Array ();
var total = Vector3.zero;
var speed = Vector3.zero;
static var G = 0.01f; // adjust with try & error
static var planets = List.<Rigidbody>();
private var myRigidbody : Rigidbody;
//for testing. Set the z value to give the planet an initial speed along it's z-axis
public var initialForwardSpeed : Vector3;
function Awake()
{
myRigidbody = rigidbody;
myRigidbody.velocity = transform.TransformDirection(initialForwardSpeed);
}
function OnEnable()
{
planets.Add(rigidbody);
}
function OnDisable()
{
planets.Remove(rigidbody);
}
function FixedUpdate()
{
var pos = myRigidbody.position;
var acc = Vector3.zero;
for(var planet in planets)
{
if (planet == myRigidbody)
continue;
var direction = (planet.position - pos);
acc += G * (direction.normalized * planet.mass) / direction.sqrMagnitude;
}
myRigidbody.velocity+= acc * Time.fixedDeltaTime;
}
function calculate ()
{
for (k=0;k<numberOfPlanets;k++)
{
var indiv = planets [k];
total = Vector3.zero;
for(j=0;j<numberOfPlanets;j++)
{
var planetRef = planets[j];
var direction = (planetRef.position-indiv.position);
total += (direction.normalized * masses[j]) / direction.sqrMagnitude;
speed[k] += total;
indiv.transform.Translate (speed[k]);
}
}
}
Error message: Assets/Script.js(13,12): BCE0089: Type 'Script' already has a definition for 'planets'. If I delete a variable, I get much more errors. What should I do?
You can't have two variables with the same name, that's just crazy! How should the compiler know which variable you want to use?
Sorry, I'm a total beginner when it comes to Scripting. Which variable(s) should I rename or delete? Thanks in advance.
I just said you can't have two variables with the same name, therefore any variables which are defined more than once.
Answer by screenname_taken · Mar 23, 2014 at 02:05 PM
One of the two "planets" one. Just change it to something else, in all the lines referring to that one. If you change the planets variable in line 13 for example, you should change the planets variable in lines 26,31,40 that refer to rigidbodies.