How to make Gravity for multiple planets in Unity3d - unity3d

What i'm looking to do is something similar to our solar system, where you are gravitically drawn to one planet till you leave it's pull, and then once you're on another planet be drawn to that gravity.
I have found many entries online about how to create gravity for a single planet, but none i've found work for multiple sources.
Any help would be GREATLY appreciated.
Projects I've already looked at were mainly for single planet gravity.
unity 3.3, create local gravity on object
http://answers.unity3d.com/questions/13639/how-do-i-make-a-small-planet-with-gravitational-pu.html
http://answers.unity3d.com/questions/701618/how-could-i-simulate-planetary-gravity-that-has-an.html

This could be done easily by adding a normal force relative to the planet on the surrounding objects.
According to physics of Universal gravitational force you can calculate the gravitational force. Then calculated the normal force at the moment and add the force.
void FixedUpdate(){
// Do the Force calculation (refer universal gravitation for more info)
// Use numbers to adjust force, distance will be changing over time!
forceSun = G x (massPlanet x massSun)/d^2;
// Find the Normal direction
Vector3 normalDirectionSun = (planet.position - sun.position).normalized;
// calculate the force on the object from the planet
Vector3 normalForceSun = normalDirection * forceSun;
// Calculate for the other systems on your solar system similarly
// Apply all these forces on current planet's rigidbody
// Apply the force on the rigid body of the surrounding object/s
rigidbody.AddForce(normalForceSun);
// .... add forces of other objects.
}
With various m1, m2 values you will be able to make the system more realistic. As an example make the object move/accelerate towards the planets with higher mass.

Related

How to make object pull another in Unity 2D

So I'm trying to simulate orbital mechanics in Unity 2D. I have a ship and Moon model in scene. I calculated the sphere of influence, and if the distance between the Moon and ship is smaller than sphere of influence, the gravity will effect. Problem is;
I can't get gravity affect working.
I've tried using AddForce method, but since it requires Vector2 elements and I calculate my force as float (I use Newton's law of gravitation formula and I get a float), I don't know how to include my float force in Vector2 force.
force = (GravitationalConstant * ((planetMass * ship.GetComponent<Rigidbody2D>().mass)/Mathf.Pow(Vector3.Distance(ship.transform.position,transform.position),2)))/(realityConstant * forceReducer);
if (Vector3.Distance(transform.position,ship.transform.position) < SOI/realityConstant){
ship.GetComponent<Rigidbody2D>().AddForce(new Vector2((float)force,0f));
}
This code makes Moon pull the ship to itself only from left side. When ship passes Moon, it keeps pushing it to right. Not to itself.
I need a fix, that makes Moon pull the ship to itself everytime, with a specific force. How do i make this happen?
Any idea would be helpful.
Thanks a lot!
Force is applied using a vector. You have the magnitude of your vector but not its direction. You can calculate a direction by subtracting moon position from the ship position:
ship.GetComponent<Rigidbody2D>().AddForce((Moon.transform.position -
ship.transform.position).normalize * force);

Why a big moving attractor object gives a slingshot to other object with using gravity formula rather than holding it?

I have a big spherical Gameobject which moves forward in 3D with constant velocity. I have other spherical objects that other big object needs to attract to itself. I am using Newton's law of universal gravitation formula to attract other objects, but as expected, other objects are doing a slingshot movement much like the space shuttles doing when needed with other planets' orbits to accelerate.
I actually want a magnetic effect that without taking the masses into account, all other objects will be catched by the big object. How can I do that? Do I need a different formula? Or do I need to change the movement behavior of the objects altogether?
If I got it right you expect to have something like this: https://www.youtube.com/watch?v=33EpYi3uTnQ
You can do a spherical raycast or have an sphere collider as trigger to detected the objects that are inside of your magnetic field.
Once you know those objects you can calculate the distance from each of them to the magnetic ball.
You can make an inverse interpolation to know how much strength/"magnetism" is getting into that object.
Then you can apply some force on the attracted object towards the magnetic ball's center.
Something like this algorithm:
var objectsInsideField = ListOfObjects;
foreach (o in objectsInsideField) {
var distance = (o.position - center.position).magnitude;
var strength = distance / fieldRadius; // fieldRadius == spherical radius
o.AddForce(dir: o.position - center.position, strength: strength)
}
Of course, you need to do some adjustments and probably add some multipliers to make the force to be meaning.
The final result should be: for each sequential frame, if the object is inside the magnetic field it moves towards the center a bit. The next frame it should be even close to the center so the strength is even bigger.. and so and so.
First of all, since the big objects is moving with constant velocity, a coordinate frame with axes parallel to the axes of the original coordinate system will be moving uniformly with constant velocity, so this new moving coordinate system is also inertial and you can write all your equations of motion in it, calculate everything with respect to it, and at the end you add the uniform movement to the results. The benefit is that the big object is stationary in this coordinate system, so simpler physics applies.
The slingshot effect occurs most likely because your objects are treated as mass-points, rather than bigger 3D entities (like spheres), for which the centers of mass never get too close enough. Hence maybe some sort of collision detection may eliminate this problem, especially if you decrease significantly or kill completely the elastic collision resolution.
All of what I am saying is a bit speculative as I have no access to details.

How to use AddForce and Velocity together?

I have the jump component who use the AddForce for jumping and the movement component who move left and right using the Velocity.
If you don't move the character when your are jumping the jumping will be fine but when you move the character and jump at the same time then the movement component will break the jumping because the velocity is setting up a Vector2 point where define the Y axis too. I tried to use the current Y axis from the transform component in the movement but even that doesn't work.
What I should do for fix the problem between AddForce and then use Velocity?
It seems your move function is creating a new velocity vector and overwriting the existing one.
Vector2 velocityVector = rigidbody.velocity;
velocityVector.x += movement * force;
rigidbody.velocity = velocityVector;
This will retain the existing velocity, both X and Y, and modify it. You will of course need to add deceleration (usually I use something along the lines of if(grounded) velocityVector.x *= 0.999f;, but I'm sure more fancy maths exists for more realistic deceleration) and some kind of maximum speed (again, I keep things simple and use similar to if(velocityVector.x > maxSpeed) velocityVector.x = maxSpeed;).
Rigidbody.AddForce has the following definition:
public void AddForce(Vector3 force, ForceMode mode = ForceMode.Force);
One of the options available for ForceMode is ForceMode.VelocityChange:
Add an instant velocity change to the rigidbody, ignoring its mass.
Apply the velocity change instantly with a single function call. In contrast to ForceMode.Impulse, VelocityChange will change the velocity of every rigidbody the same way regardless of differences in mass. This mode is useful for something like a fleet of differently-sized space ships that you want to control without accounting for differences in mass. In this mode, the unit of the force parameter is applied to the rigidbody as distance/time.

How does SpriteKit physics move bodies?

How does SpriteKit's physics engine (Box2d) move bodies and apply gravity to them?
is it just the standard:
velocity = velocity + gravity
position = position + velocity * deltaTime
or is there a more complex equation.
I ask this because I am trying to calculate the trajectory of the body and plot it.
Simplified, this is correct. However there can be other forces acting on a body (collisions, joints) and thresholds (ie stop moving if velocity below threshold, etc) and floating point rounding errors can add up.
So if you're looking for a forward calculation it depends on how precise it needs to be.
The most precise option would be to actually run the simulation to advance it to see where bodies will be - however since SK doesn't give you the Box2D sources this can't be done, ie you can't copy the world state and advance it manually in a copy of the current world.

Box2d - Giving an object attraction / gravity

I am using Box2d to simulate a top-down space like environment. I have an object that has an impulse applied and will be flying (through space) near to a "planet". The world itself has no gravity but I would like to set up Planets and Stars with individual gravity such that other dynamic objects will fall / be pulled in towards them. How can I achieve this?
If you have small count of bodies/stars you can just apply gravity forces to your bodies each time before calling Step() function.
But I think it will become really slow if the system gets big. If your stars and planets are not moving you are able to precalculate the total gravity force in each point of 2D space. Store this precalculated values of gravity in some 2D array (with some step) and then apply the forces from this lookup table