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);
}
}
↧