Im in the process of creating a 2D Physics-based space exploration game. I created a script which takes Objects from a list and applies Gravity to them based on Newton’s Formula, here is the script:
public class GravityConfig : MonoBehaviour
{
public List<GameObject> GravList;
private Rigidbody2D rb2;
public float GravitationalConstant;
public Vector3 ForceApplied;
private float maxGravityDist = 0.01f;
private Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
public void Gravity()
{
foreach (GameObject x in GravList)
{
rb2 = x.GetComponent<Rigidbody2D>();
maxGravityDist = rb2.mass * 10;
float dist = Vector2.Distance(x.transform.position, transform.position);
Vector2 v = x.transform.position - transform.position;
ForceApplied = v.normalized * GravitationalConstant * (1.0f - dist / maxGravityDist) * rb2.mass * Time.deltaTime;
rb.AddForce(ForceApplied);
}
}
private void FixedUpdate()
{
Gravity();
}
}
As you may know, The speed at which an object falls actually has nothing to do with its mass but rather the gravitational field strength of the body it is falling towards. Unfortuantely, RigidBody2D.AddForce() uses the mass of the RigidBody to calculate it’s velocity. Using Rigidbody rather than Rigidbody2D however, there is an option to use ForceMode.Acceleration which applies a force to said rigidbody without the use of its mass. This is great because in my game, I want all objects to fall at the same speed regardless of its mass. Unfortunately, there is no such option for RigidBody2D and i cant find a workaround that doesn’t involve me rewriting the whole game. I thought i would come to the forums to request help from more seasoned game developers like you guys.
thanks in advance,
Ethan