- Home /
3D Planatary Gravity
I am using RigidBodies and want my planets to use real physics bases off of their mass and want to have that gravity to interact with other RigidBodies in the system.
Answer by syclamoth · Apr 18, 2012 at 12:42 AM
Step 1: Turn off gravity
Step 2: Create some kind of 'forcefield' script on your planets. There are a lot of ways of doing this, but the simplest one would be to use Physics.OverlapSphere and then apply forces to everything in that area. Here's a sample:
// Make sure to add the line 'using System.Collections.Generic'
// on the first line of the file
public float forceRadius = 20;
public float gravPower = 9.81f;
void FixedUpdate()
{
// Populate a list of nearby bodies
List<Rigidbody> bodies = new List<Rigidbody>();
foreach(Collider col in Physics.OverlapSphere
(transform.position, forceRadius))
{
if(col.attachedRigidbody != null && !bodies.Contains(col.attachedRigidbody))
{
bodies.Add(col.attachedRigidbody);
}
}
// Now you have your rigidbodies, time to add the force!
foreach(Rigidbody body in bodies)
{
float bodyDist = (body.position - transform.position).sqrMagnitude;
float gravStrengthFactor = Mathf.Pow(forceRadius) / bodyDist;
body.AddForce(gravStrengthFactor * gravPower *
(transform.position - body.position) * Time.deltaTime, ForceMode.Acceleration);
}
}
Of course, there are a whole slew of optimisations you can apply to this, but it's a start.
Step 3: Write a simplified physics engine to simulate interactions between the large 'gravity generator' objects, since they would kind of break themselves if they could affect themselves.
Would applying forces not produce "repulsion" as opposed to attraction? Wouldn't gravity have to do solely about attraction?
What's the difference between 'repulsion' and 'attraction'? The direction of the force, that's what. Have you tried the script? I think there are some issues with the falloff calculation, but the basic concept is sound.
Answer by kolban · Apr 18, 2012 at 12:29 AM
Unity's physics engine only simulates gravity from one gravitational body. The RigidBody objects have a force applied to them in the down (-ve Y) axis only. There is no concept of creating additional gravity fields/forces that would act as attractors to other objects.
Your answer
Follow this Question
Related Questions
Creating 3d planets with terrain and atmosphere 3 Answers
How to make a character walk on a 3D cube planet and a long 3D cube planet using gravity? 2 Answers
Planet gravity help need guidance no code 1 Answer
How do I add gravity in code? 1 Answer
How to stop a mesh from falling through 3D objects. 0 Answers