thomfur
1
Hello,
I am trying to make a 2D game based firing objects that are affected by planets gravity. Unfortunately I don’t know how to make the point gravity for the plants. If you could point me in the right direction that would be great.
Thanks,
Tom
For each object moving, you will need to generate a force towards each planet for each frame. Here is a sample script:
#pragma strict
var maxGravDist = 4.0;
private var planets : GameObject[];
var maxGravity = 35.0;
function Start () {
planets = GameObject.FindGameObjectsWithTag("Planet");
}
function FixedUpdate () {
for(var planet : GameObject in planets) {
var dist = Vector3.Distance(planet.transform.position, transform.position);
if (dist <= maxGravDist) {
var v = planet.transform.position - transform.position;
rigidbody2D.AddForce(v.normalized * (1.0 - dist / maxGravDist) * maxGravity);
}
}
}
This code assumes that all your planets are tagged ‘Planet’. This code goes on the ship or projectile. This is sample code. For real code, I’d create an array of transforms from the array of game objects, and I’d cache the local transform to make things a bit more efficient. ‘maxGravDist’ defines the maximum distance from the planet the gravity is applied, and maxGravity is the maximum amount of force applied each frame. The equation makes the gravity drop off linearly. Real gravity drops off as the square of the distance, but usually a linear dropoff works well in games.
Hi,
This is a discussion with further links on planetary gravity. What you could do is use Newton’s Universal Law of Gravitation:
F = (G * m1 * m2) / (Distance^2)
If you only want this gravity to apply to the objects, then all you need to do is calculate the total gravitational force applied to the bullet from all planets (or, to reduce the computation, only use planets that are within the objects’s arbitrary vicinity).
Since force (F) is a vector, the total force of the object will give you a magnitude and direction in which to apply the force on the objects. Note that for the distance in the formula you will have to use a Vector (planet - object) for this to work.