To figure out a basic implementation of a "spherical gravity," let's look at how gravity works in normal, Newtonian physics. Here is the equation that you probably learned in high school physics:
$$F_g=\frac{G\cdot m_{\text{earth}}\cdot m_{\text{object}}}{r^2}$$
where $F_g$ is the force on the object due to gravity, $G$ is the gravitational constant, $m_{\text{earth}}$ is the mass of the Earth, $m_{\text{object}}$ is the mass of the object, and $r$ is the distance between the Earth and the object. Since $G$ and $m_{\text{earth}}$ are always the same on earth, we often simplify the equation as follows:
$$F_g=9.81\cdot\frac{m_{\text{object}}}{r^2}$$
The only issue with our formula is that we don't have any direction for our gravity. In normal physics we just assume that it is straight down (if we're getting technical, $9.81$ is a vector quantity that gives us our direction). We can't make this assumption inside of our sphere. To find the direction, we can multiply our gravity by the normalized location of our object (a vector with a length of $1$ pointing directly at our object):
$$F_g=9.81\cdot\frac{m_{\text{object}}}{r^2}\cdot\hat{\mathbf s}$$
where $\hat{\mathbf s}$ is the normalized location vector.
Now that we have a formula to calculate the gravity, we can write a Python script. This script must be run every logic tic on every object that will be affected by gravity, like this:
Script:
import bge
radius = 20
g = 9.81
obj = bge.logic.getCurrentController().owner
loc = obj.worldPosition
len = loc.length
try:
gravity = loc.normalized() * obj.mass * g / (radius - len) ** 2
except ZeroDivisionError:
gravity = [0,0,0]
obj.applyForce(gravity)
This will find how far the object is from the origin, then push it away from the origin, using a linear interpolation to vary the force from 0
at the center, and 9.8
at the edge of the sphere (defined as 20
).
Here is an basic example .blend
file. You can move the sphere with A, S, D, W, Q, and E. It will start motionless in the middle, then become pulled faster and faster as it gets closer to the enclosing sphere. Tapping Spacebar will make the sphere jump towards the origin.