I’m making a 2-d platformer game. I want to have a lot of small planets that the player can jump between, so I conjured up the following script which calculates the gravitational force of the planet on the player.
var player:Transform;
var distance_squared : float;
var force : float;
var force_vector : Vector3;
var force_direction:Vector3;
var gravitational_constant : float;
function Update ()
{
gravitational_constant = 1;
distance_squared = (transform.position - player.position).sqrMagnitude;
var mass1 = 1000;
var mass2 = 1;
force = gravitational_constant * ((mass1 * mass2) / distance_squared);
force_direction = (transform.position - player.position).normalized;
force_vector = force_direction * force;
rigidbody.mass = mass1;
player.rigidbody.mass = mass2;
player.rigidbody.AddForce(force_vector);
}
The problem is that the “planet” that this is assigned to is just a plane with a circular Texture applied to it, and therefore, the player just goes right through the “planet”. To (try to) fix this, I assigned the following code to the player:
var Mars : Transform;
var hit : RaycastHit;
var NormalTimesGravity : Vector3;
function Update ()
{
if (Physics.Raycast (transform.position,Mars.position-transform.position,hit,1))
{
NormalTimesGravity=(hit.normal*Mars.GetComponent(Gravity).force);
Debug.DrawRay(transform.position,Mars.position-transform.position);
rigidbody.AddForce(NormalTimesGravity);
}
For whatever reason, this code only seems to slow down the player and not stop him completely. My thought was that the “planet”'s surface needed to push the player in the normal direction of the player with the magnitude of the gravitational force the player has. That is how physics works in real life, is it not? For example, a 100 gram object with a gravitational acceleration of 9.81 (Earth’s gravitational pull), The surface of Earth is pushing the object up at 981 N in the normal direction. So why therefore is this script not stopping the object completely.
P.S. if I do something like if (Physics.Raycast (transform.position,Mars.position-transform.position,hit,3))
(increase the number in the Raycast), the object will not go through the planet (it stops before it hits the surface), but it also just bounces along the 3 meters out from the planet’s surface.