- Home /
Realistic gravity much too strong
I'm creating a game with realistic gravity and orbital mechanics, but when I plug in numbers for the mass of the planet, the gravity created is much much stronger than it realistically should be. I believe there is some kind of unit conversion error, but I can't figure out what that would be. Thanks for any help you guys could provide.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gravity : MonoBehaviour
{
public GameObject planet;
public GameObject ship;
private Vector3 planetPosition;
private Vector3 shipPosition;
public Rigidbody shipRigidbody;
private float shipMass = 2000.0f;
private float planetMass = 86700000000000000000.0f;
Vector3 startVelocity = new Vector3(0f, 0f, 0f);
//Newtons Gravity Equation
public Vector3 calculateForce()
{
//Find the positions of the objects
planetPosition = planet.transform.position;
shipPosition = ship.transform.position;
//Distance between the objects (r)
float distance = Vector3.Distance(planetPosition, shipPosition);
//Distance squared (r^2)
float distanceSquared = distance * distance;
//Gravitational Constant (G)
float G = 6.67f * Mathf.Pow(10, -11);
//F = G*m*m / r^2
float force = G * ((planetMass * shipMass) / (distanceSquared));
//Get the heading
Vector3 heading = (planetPosition - shipPosition).normalized;
//Turn the force from just a value into a 3D vector with direction
Vector3 forceWithDirection = (force * (heading/heading.magnitude));
//Return Force
return (forceWithDirection);
}
void Start()
{
//Give Ship initial velocity
shipRigidbody.AddForce(startVelocity, ForceMode.VelocityChange);
}
// Update is called once per frame
void FixedUpdate()
{
//Calculate and add the force of gravity to the ship
shipRigidbody.AddForce(calculateForce() * 0.1f, ForceMode.Impulse);
}
}
Answer by Vollmondum · Feb 21, 2021 at 06:05 AM
Seems like you're trying to fit 20-digit value into a float, so it cuts along the way. Try using double
Alright, I didn't know that was a thing. I'll let you know what the results are, thanks.
So I tried it out, and while the function returns the expected force value (aprox 60N), the acceleration I get is still much higher than I would have expected. I would have expected an acceleration of 0.029m/s^2, but I get more like 3ish m/s^2.
Could this be due to the rate at which the physics engine updates?
There's DRAG setting in rigidbody, which is air resistance. Physics settings is pretty tough to master. The other day I spent 4 hours adjusting a platformer. Just play around till you get expected behavior
Thanks, I eventually figured out the right numbers.