**sorry i speak french **

How to do that:

I want to make a cubic planets game with gravity. I want to the player rotate when they are in top or on the axi of a face of the block. if a player don’t touch the face, he will affected by gravity for touch-it. Note: if the player are far of the planets, he won’t be affected by gravity. Block building game

Firstly, we need a method for calculating the gravitational force between two bodies. The following is a loose implementation of Newtons law of Universal Gravitation, but you could use linear, quadratic, etc falloff:

```
public const float G = 1000.0f;
public static float UniversalGravitation(Rigidbody a, Rigidbody b)
{
return G * (a.mass * b.mass) / Vector3.Distance(a.transform.position, b.transform.position);
}
```

Now we need to figure out the direction of the gravity (I’ll do this in 3D because you didn’t specify 2D or 3D):

```
private static Vector3[] s_GravityDirections = {Vector3.up, Vector3.down, Vector3.left, Vector3.right, Vector3.forward, Vector3.back};
public static Vector3 CubeGravityForce(Rigidbody planet, Rigidbody other)
{
float gravity = UniversalGravitation(planet, other);
float bestDot = -1.0f;
Vector3 direction = Vector3.zero;
for (int index=0; index < s_GravityDirections.Length; index++)
{
Vector3 gravityDirection = planet.transform.TransformVector(GravityDirections[index]);
Vector3 directionToOther = other.transform.position - planet.transform.position;
float dot = Vector3.Dot(gravityDirection.normalized, directionToOther.normalized);
if (dot > bestDot)
{
direction = gravityDirection;
bestDot = dot;
}
}
return gravity * direction.normalized * -1.0f;
}
```

And I think that should work.

Edit:

For rotation you can simply calculate the direction of the force in the same way as gravity direction, and pass that as your “up” into Quaternion.LookRotation.

To cutoff the gravity after a certain distance you can simply check the distance and return 0.0f.