// Start is called before the first frame update void Start() { rb = GetComponent <Rigidbody2D>(); gravObj = GetComponent <gravityObject>(); //enginePower = maxEnginePower; fuelAmount = maxFuel; }
public void applyGravityForce(gravityObject affected, gravityObject affecting) { //print ("applyGravityForce"); Vector3 affectedXYZ = affected.transform.position; Vector3 affectingXYZ = affecting.transform.position; float distance = (affectedXYZ - affectingXYZ).magnitude; Vector3 direction = (affectingXYZ - affectedXYZ).normalized; float force = (affected.masse * affecting.masse * gravityConstant) / Mathf.Pow(distance, 2); //print ("force : "+force); affected.GetComponent <Rigidbody>().AddForce(force * direction); }
// The attract function is where we will compute all of the mathematics behind Newton's Law of Universal Gravitation void Attract(gravityObject objToAttract) { //We get the rigidbody component from the object that was passed. Remember this contains all of the information about an objects mass. Rigidbody rbToAttract = objToAttract.rb; //We then determine the direction by subtracting the two rigidbody's positions. A position is represented by a Vector 3 in Unity. If you're unfamiliar with Unity, this is the X, Y, and Z axis of 3-Dimensional space Vector3 direction = rb.position - rbToAttract.position; //We can get the distance from our direction vector by reading it's magnitude and putting that into a variable. In Unity a Vector 3, will have a magnitude which is the same as a distance. float distance = direction.magnitude; //We then do Newton's equation: F = G * (M1 * M2) / R^2 float forceMagnitude = G * (rb.mass * rbToAttract.mass) / Mathf.Pow(distance, 2); //We then have to normalize the direction we took earlier, which remember was a Vector 3. By normalizing it, we set it's magnitude(or distance) to 1. We multiply that normalized Vector 3 by our //forceMagnitude and add that force to the object that we are attracting. Vector3 force = direction.normalized * forceMagnitude; rbToAttract.AddForce(force); }