- Home /
GameObject to GameObject gravity
I'm working on a planetary mining game and I'm trying to figure out how to apply gravity to Earth and the Moon, using empty GameObjects as triggers. I have set layers of empty GameObjects on both the Earth and Moon. I want it so that when an Asteroid hits a trigger it gets pulled in faster. I'm doing this in C# so id prefer any advice in that language.
Would you not be better off just calculating the distances between things rather than using triggers?
Answer by robertbu · Jun 20, 2013 at 04:14 PM
If you want to use triggers, you could do something like:
void OnTriggerStay(Collider other) {
if (other.name == "moon") {
Vector3 v3 = other.transform.position - transform.position;
v3 = v3.normalized * moonPull;
rigidbody.AddForce (v3);
}
}
Note this applies a constant force. Depending on your game, you may want to scale the force based on the distance.
Depending on your game, there may be a much better way. Use Rigidbody.AddExplosionForce() with a negative value. It gives a radius, so you can limit the range to your "trigger" zone. And you can put one in for each object that has pull. The force will drop off linearly:
rigidbody.AddExplosionForce(maxEarthForce, earth.position, maxEarthRadius);
rigidbody.AddExplosionForce(maxMoonForce, moon.position, maxMoonRadius);
maxEarthForce and maxMoonForce must be negative values in order form them to pull in the objects. And unless you need it for your game play, there is no trigger zone needed.