Sign in to follow this  

Help with making a gravity well.

This topic is 2046 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to make a gravity well so some object with a velocity will spiral in towards the center of the well as it orbits it. What I have appears to start to work, but then the object circling the well suddenly will fly off away from the well. Here is the code I am using

[code]

Vector3 gravDir = curGravWellPos - transform.position;
gravDir = gravDir.normalized;

float dT = Time.time - startTime; //current time minus the start time
float dTSqrd = dT * dT;
float deltaY = (velocity.y * dT) + (.5f * grav * gravDir.y * dTSqrd);
float deltaX = (velocity.x * dT) + (.5f * grav * gravDir.x * dTSqrd);

transform.position = startPos + new Vector3(deltaX, deltaY, 0);
[/code]

Another issue I'm having is that when calculating deltaY and deltaX, I'm pretty sure I should be using subtraction. But if I do that, the object doesn't move towards the gravity well at all. Edited by homer_3

Share this post


Link to post
Share on other sites
[CODE]Vector3 gravDir = curGravWellPos - transform.position;[/CODE]
should be
[CODE]Vector3 gravDir = transform.position - curGravWellPos;[/CODE]
as you want to translate your objects so that the gravity well is at the origin, not the other way around. This might resolve your subtraction dilemma, but your equation here doesn't make much sense to me. The acceleration used in the kinematic equations should be derived from Newton's law of gravitational attraction (which takes into account the distance of the object to the gravity well). It is not a constant, but this:

F_g = G * (object.mass * well.mass) / (object-well distance)^2 where G is the gravitational constant (it can also be arbitrary if you have accuracy problems with large masses).

And you obtain the acceleration on the object by dividing F_g by the object's mass. Maybe you are already doing this as you don't show what "grav" is. You will probably also want to apply energy conservation to prevent objects slingshotting themselves and some kind of handling in case the object comes really close to the well (infinite gravitational force).

Can you give a bit more detail (what does "flies off away" mean, does it just stop responding to the well and keep going at constant velocity in a straight line or accelerates away from the well? etc...). Edited by Bacterius

Share this post


Link to post
Share on other sites
I thought you subtracted the position of the other guy from yourself to get a vector going from yourself to the other guy.

Using the projectile motion equation to get the distance traveled made sense to me. But instead of only accounting for gravity on the Y, I also added in X modified gravity's proportion in each equation by the normalized vector that points to the gravity well. But I really wasn't sure what physics equation would be best to use to do this simulation.

Getting the acceleration based on the distance the object is from the well isn't all that important to me. A constant acceleration will work just fine.

As for flying away: The thrown object starts in the top center of the screen and is thrown down and to the left. The well is in the center of the screen. For a few seconds, the object moves towards the gravity well as expected, but then it just starts moving in a straight line up and to the left.

Share this post


Link to post
Share on other sites
I noticed that your version doesn't update the velocity vector at all. I think it might be better to go back to basics, often the best way when calculations don't pan out:

1. Calculation the force due to gravity, as per Bacterius's post.
2. Convert it to acceleration, using F=ma.
3. Make the acceleration into a vector, e.g. the unit vector towards the gravity source times a.
4. Update the velocity with the acceleration and time, e.g. add the acceleration vector times the time.
5. Add the velocity to the position.

You can get fancier on top of that, e.g. interpolate the acceleration from one frame to another, then interpolate the velocity based on that, then get the position. Calculus in the house. ;) But that should be a good start if you run your physics frequently.

Also note the slingshot effect if an orbiting body gets too close. If your objects lack a physical radius they can get arbitrarily close, which yields funky results. Also note that at extreme close range treating a gravitational source as a point doesn't work well, unless it is in fact a point like a black hole.

Share this post


Link to post
Share on other sites
[quote]Also note the slingshot effect if an orbiting body gets too close. If your objects lack a physical radius they can get arbitrarily close, which yields funky results. Also note that at extreme close range treating a gravitational source as a point doesn't work well, unless it is in fact a point like a black hole.[/quote]
Actually black holes do have a physical radius too, called the event horizon (once an object crosses that boundary its state is in fact irrelevant as per relativity which dictates it should become unobservable), and it can be quite large. Newton's law of gravitational is mathematically sound but is simply not designed to work at arbitrary close ranges because then you need increasingly many time steps to keep the simulation stable. Fortunately naked singularities don't exist in reality (as far as we can tell). In general this isn't a problem though unless you actually start playing with n-body simulations in which a robust simulation is critical.

Share this post


Link to post
Share on other sites
Damn my loose tongue. ;) I didn't literally mean they have no radius, but compared to a sun their radius is negligible, and you would likely fall into the event horizon before the traditional gravitational effects of close range to a massive object become apparent. I doubt the OP wants to get into relativity either way.

Share this post


Link to post
Share on other sites
[quote name='homer_3' timestamp='1336532148' post='4938565']
I thought you subtracted the position of the other guy from yourself to get a vector going from yourself to the other guy.
[/quote]

You have it backwards.

[quote name='homer_3' timestamp='1336532148' post='4938565']
Getting the acceleration based on the distance the object is from the well isn't all that important to me. A constant acceleration will work just fine.

[/quote]

Then you are not modeling a gravity well, but something else... which might explain why it doesn't behave like you expect. Edited by Olof Hedman

Share this post


Link to post
Share on other sites
Another thing worth mentioning is that a real, physically accurate gravity field cannot "catch" stray objects and make them spiral into itself. This is only possible if you add some sort of friction that dampens motion over time. Would you like to see some simple code samples (100-200 lines) of gravitational interaction?

Cheers,
Mike

Share this post


Link to post
Share on other sites
[quote name='jefferytitan' timestamp='1336545575' post='4938590']
I noticed that your version doesn't update the velocity vector at all. I think it might be better to go back to basics, often the best way when calculations don't pan out:

1. Calculation the force due to gravity, as per Bacterius's post.
2. Convert it to acceleration, using F=ma.
3. Make the acceleration into a vector, e.g. the unit vector towards the gravity source times a.
4. Update the velocity with the acceleration and time, e.g. add the acceleration vector times the time.
5. Add the velocity to the position.

You can get fancier on top of that, e.g. interpolate the acceleration from one frame to another, then interpolate the velocity based on that, then get the position. Calculus in the house. ;) But that should be a good start if you run your physics frequently.
[/quote]

I didn't update the velocity because dY = Vy0*t = .5*a*t^2 doesn't call for it. I'll try out your method of simply updating the velocity based on the acceleration instead of getting dY and see how that works out.

[quote name='Olof Hedman' timestamp='1336554565' post='4938611']
[quote name='homer_3' timestamp='1336532148' post='4938565']
I thought you subtracted the position of the other guy from yourself to get a vector going from yourself to the other guy.
[/quote]

You have it backwards.
[/quote]

Say the well is at 8,2 and the object is at 4,6.

8-4 = 4
2-6 = -4

This gives me a vector of 4,-4. Adding that vector to 4,6 (the object caught in the well) will put me at the center of the well. I don't see how subtracting my target's position from my position will give me a vector going from me to the target.

[quote name='Olof Hedman' timestamp='1336554565' post='4938611']
[quote name='homer_3' timestamp='1336532148' post='4938565']
Getting the acceleration based on the distance the object is from the well isn't all that important to me. A constant acceleration will work just fine.

[/quote]

Then you are not modeling a gravity well, but something else... which might explain why it doesn't behave like you expect.
[/quote]

I'd expect a constant acceleration to still pull the object towards the well...

[quote name='h4tt3n' timestamp='1336558107' post='4938622']
Another thing worth mentioning is that a real, physically accurate gravity field cannot "catch" stray objects and make them spiral into itself. This is only possible if you add some sort of friction that dampens motion over time. Would you like to see some simple code samples (100-200 lines) of gravitational interaction?

Cheers,
Mike
[/quote]

So you are saying that if you were out in space and tried to throw a baseball tangent to Earth and the basball wasn't moving at escape velocity, it wouldn't fall to Earth?

Share this post


Link to post
Share on other sites
[quote]
So you are saying that if you were out in space and tried to throw a baseball tangent to Earth and the basball wasn't moving at escape velocity, it wouldn't fall to Earth?
[/quote]

Yup, it would make a circular or elliptic orbit around the Earth and hit you in the neck. If you went out of the way, it would stay in that orbit forever (unless influenced by other forces, like friction, gravity from other bodies ect.)

If this is for some "angy birds space" clone, then be warned that the game is very far away form beeing physically accurate.

I won't mind finding some code for you to look at if that is any help.

Cheers,
Mike

Share this post


Link to post
Share on other sites
[quote]I'd expect a constant acceleration to still pull the object towards the well...[/quote]
It's not constant. Basically the pull becomes stronger and stronger as you get closer to the well, and follows a inverse-squared relationship with distance. It's why it's called a well, you fall faster and faster in it (a black hole is your ideal well, with perfectly* vertical sides, from which is it impossible to escape, "normal" wells are more akin to the three-dimensional analogue of a funnel).

* this is not quite true, in fact the sides just need to be "vertical" enough to make the escape velocity of the gravitational field higher than the speed of light [eqn]c[/eqn].

And anyway, acceleration depends on mass, from [eqn]F = ma[/eqn]. If two objects of different masses are subjected to an identical force, they will accelerate at different rates. Imagine you kicking the ground. You apply a force [eqn]F[/eqn] on the Earth, and the Earth exerts a force [eqn]F[/eqn] on you (Newton's third law). Then the acceleration on you is [eqn]\frac{F}{m_{\mathrm{you}}}[/eqn] which is fairly small (considering your kick delivered at best 25N, and you probably weigh at least 50kg) (this is absorbed by your body which explains why kicking the ground hurts your leg instead of pushing you upwards) On the other hand, the acceleration on the Earth is [eqn]\frac{F}{m_{\mathrm{earth}}}[/eqn] which is, for all practical purposes, zero. If you didn't apply [eqn]F = ma[/eqn] and directly used force as acceleration, the Earth would be flung backwards a significant distance every time you kicked it, which clearly doesn't happen.

[quote]I didn't update the velocity because dY = Vy0*t = .5*a*t^2 doesn't call for it. I'll try out your method of simply updating the velocity based on the acceleration instead of getting dY and see how that works out.[/quote]
From the above, kinematics are inapplicable because the acceleration isn't constant. In fact in your first post's code the acceleration isn't constant anyway because of the gravDir unit vector (so kinematics can't be applied there anyway). You will want to keep track of position and velocity and repeatedly apply forces on the object every physics step. Edited by Bacterius

Share this post


Link to post
Share on other sites
Not that this matters a whole lot to a lot of people, but a real, physically accurate gravitational field [i][b]can and does[/b][/i] indeed "catch" stray objects and make them spiral into itself, but the effect is quite negligible for the Earth in orbit around the Sun. Basically, any large accelerating mass and/or large rotating axially asymmetric mass (ie. anything producing a time-dependent metric) will shed energy-momentum-mass-pressure-viscosity as gravitational radiation, and the result will be shrinking bodies and shrinking orbits. Black hole mergers are the most extreme example of this, and the effect has been observed in the behaviour of binary stars. [url="http://en.wikipedia.org/wiki/Gravitational_wave#Orbital_decay_from_gravitational_radiation"]http://en.wikipedia....ional_radiation[/url]

This is all somewhat, but not entirely similar to how an electron can shed momentum in the form of light when it is accelerated. This is why physicists figured that the energy-momentum levels of the electron in an atom had to be quantized. Otherwise, if an electron in an atom could shed all of its momentum, then it would definitely spiral into the nucleus and come to a screeching halt, which simply doesn't happen. [url="http://en.wikipedia.org/wiki/Bremstrahlung"]http://en.wikipedia....i/Bremstrahlung[/url]

FYI: If you can integrate the following two paragraphs into a single coherent paragraph -- without obvious inconsistencies like "doesn't the electron shed momentum and/or rest mass as gravitational radiation?" -- then you'll win a Nobel prize and eternal fame.
[url="http://en.wikipedia.org/wiki/Quantum_gravity"]http://en.wikipedia....Quantum_gravity[/url]

And yeah, these guys are absolutely right that constant acceleration is not appropriate for replicating Angry Birds Space. Constant acceleration (SUVAT equations, or even an acceleration vector of variable direction but constant length, for that matter) is only appropriate for Angry Birds/Rio/Seasons where a) the curvature of the sphere's surface is low and the local section in question (ie. the playing field) is so small that the sphere's surface (ie. floor) is practically flat, and b) the local section in question does not extend above the surface/floor to any significant extent. Basically, the playing field's total width and total height would both have to be very small compared to the sphere's radius for constant acceleration to be appropriate. See: [url="http://en.wikipedia.org/wiki/File:Gravityroom.svg"]http://en.wikipedia....Gravityroom.svg[/url]

If these two criteria aren't met, then you have to consider that a) the lines of force perpendicular to the surface actually converge (they aren't really parallel, because even space is curved in Newtonian gravity) and that b) the inverse square law means that large changes in distance can lead to large changes in acceleration (we'll skip going into the curvature of time because it isn't really related to Newtonian gravity per se, but it might be something that you'll want to look into later). In this case, you should use non-constant acceleration similar to target_acceleration_vector = G*source_mass / length(source_pos - target_pos)^2 * normalize(source_pos - target_pos) * dt, where dt is the length of your physics engine's time step.** See: [url="http://en.wikipedia.org/wiki/File:Gravitymacroscopic.svg"]http://en.wikipedia....macroscopic.svg[/url]

Obviously, Angry Birds Space contains one or more non-flat/highly curved floors per playing field, given that a lot of it is made up of circular "planets" with radii much smaller than the width and height of the playing field, and so constant acceleration is definitely not appropriate.

** LaTeX test, for fun (can't seem to do rmtext):

Direction vector pointing from target position to gravitational source position:
[eqn]\vec{D} = P_s - P_t[/eqn]

Distance from target to gravitational source:
[eqn]d = {\rm{length}}(\vec{D})[/eqn]

Unit direction vector pointing from target to gravitational source:
[eqn]\hat{D} = {\rm{normalize}}(\vec{D}) = \frac{\vec{D}}{d}[/eqn]

Mass of gravitational source:
[eqn]M[/eqn]

Acceleration vector pointing from target to gravitational source. And no, it is not proper to fudge the following equation to look like it's an inverse-cube law when teaching about gravitation, you general haters of normalization operations, heh:
[eqn]\vec{A} = \frac{G M}{d^2}\;\cdot\;\hat{D}\;\cdot\;dt[/eqn] Edited by taby

Share this post


Link to post
Share on other sites
Thanks to your guys' help I am making progress. My new code looks like

[code]

Vector3 gravDir = curGravWellPos - transform.position;
gravDir = gravDir.normalized;

float dist = Mathf.Abs(Vector3.Distance(curGravWellPos, transform.position));

grav = (float)massProduct/ Mathf.Pow(dist, 2);

velocity += ( gravDir * grav);

transform.position += ((velocity * Time.deltaTime));
[/code]

massProduct is just a very large number multiplied by G. The object is now orbiting the gravity well, but it doesn't appear to be falling into it.

P.S. No this game has absolutely nothing to do with Angry Birds.

Share this post


Link to post
Share on other sites
Cool, looking better. As mentioned, falling into a gravity well is no guarantee. An orbit is essentially constantly falling into a well but "missing" because your tangential velocity is too high. Try the simulation with your object starting motionless. I would expect it to fall directly towards your well, although what happens when it reaches it is uncertain. It could get a division by zero error when it reaches the well (e.g. massProduct / Mathf.Pow(0, 2)), it may never land directly on the well and assume a linear (or rather flattened elliptical) orbit, or due to rounding errors the orbit may become more elliptical and/or slingshot.

If you want the orbit to decay, think about satellites. Their orbits can decay when they dip into Earth's atmosphere. You could simulate that, e.g. pick a radius around the well that experiences friction.

Share this post


Link to post
Share on other sites
[quote name='jefferytitan' timestamp='1336609931' post='4938830']
If you want the orbit to decay, think about satellites. Their orbits can decay when they dip into Earth's atmosphere. You could simulate that, e.g. pick a radius around the well that experiences friction.
[/quote]

I am quite surprised that the orbit doesn't naturally decay. Partially because I know satellite orbits do and this is what I want to be guaranteed to happen. I'm not really sure how to apply friction. Would I just gradually reduce the velocity vector by some factor if it is within the specified "friction radius"?

Share this post


Link to post
Share on other sites
You don't seem to be multiplying the acceleration by Time.deltaTime. I think you need to do this, like you are already doing for the velocity. If you don't properly implement the time step entirely, then the results will only come back to haunt you later in the most subtle and devious ways. Believe me. If you do fix this error and the gravitation ends up being a little less than desired, then just bump up the mass of the gravitational source by the appropriate factor. All of this might seem like a useless book balancing act, but it's very important to implement the time step properly and entirely.

Oh, and if you change from Euler integration to Runge-Kutta, etc integration later, you may find that you need to switch the order of the velocity += and the transform.position += statements, so that velocity is updated after position is updated. It's been a while since I've done something like this, but I remember running into a major glitch when they're updated in the wrong order. Of course, if you stick to Euler integration, then the "glitch" is pretty much inconsequential and you can ignore this paragraph. Edited by taby

Share this post


Link to post
Share on other sites
[quote name='homer_3' timestamp='1336565536' post='4938648']
[quote name='Olof Hedman' timestamp='1336554565' post='4938611']
[quote name='homer_3' timestamp='1336532148' post='4938565']
I thought you subtracted the position of the other guy from yourself to get a vector going from yourself to the other guy.
[/quote]

You have it backwards.
[/quote]

Say the well is at 8,2 and the object is at 4,6.

8-4 = 4
2-6 = -4

This gives me a vector of 4,-4. Adding that vector to 4,6 (the object caught in the well) will put me at the center of the well. I don't see how subtracting my target's position from my position will give me a vector going from me to the target.
[/quote]

No subtracting the target's position from yourself is what is wrong. This is what you said: "I thought you subtracted the position of the other guy from yourself to get a vector going from yourself to the other guy".
You should as you say (now), subtract yourself from the other guy.


[quote name='homer_3' timestamp='1336532148' post='4938565']
[quote name='Olof Hedman' timestamp='1336554565' post='4938611']
[quote name='homer_3' timestamp='1336532148' post='4938565']
Getting the acceleration based on the distance the object is from the well isn't all that important to me. A constant acceleration will work just fine.

[/quote]

Then you are not modeling a gravity well, but something else... which might explain why it doesn't behave like you expect.
[/quote]

I'd expect a constant acceleration to still pull the object towards the well...
[/quote]

Yes, but the object can easily "break free" if the acceleration doesn't increase as closer as you get. Edited by Olof Hedman

Share this post


Link to post
Share on other sites
[quote name='Olof Hedman' timestamp='1336661168' post='4938991']
No subtracting the target's position from yourself is what is wrong. This is what you said: "I thought you subtracted the position of the other guy from yourself to get a vector going from yourself to the other guy".
You should as you say (now), subtract yourself from the other guy.
[/quote]

Ok, I think that we are confusing the poor guy over what amounts to a matter of notation. I roughly follow the logic given here: [url="http://galileo.phys.virginia.edu/classes/152.mf1i.spring02/GravPotEnergy.htm"]http://galileo.phys....avPotEnergy.htm[/url]

I like to use the formula [b]u = -GMm/r[/b] for the scalar potential energy. I use the derivative of [b]u[/b] with respect to [b]r[/b] to get a scalar force [b]du/dr[/b] [b]= f = GMm/r^2[/b]. By [b]f = ma[/b] and [b]a = f/m[/b], I get a scalar acceleration of [b]a = GM/r^2[/b]. I multiply [b]a[/b] by [b]V = normalize(Gravitational Source Position - Orbiting Body Position)[/b] to get the final acceleration vector [b]A[/b][b] = aV[/b] of appropriate length and direction -- [b]pointing toward the gravitational source[/b].

If you want to tell the OP to negate the direction vector [b]V[/b], then you should explain yourself better. I'm not saying that where you're coming from is entirely wrong, but that you're just using a different notation and you're missing a minus sign somewhere in your explanation (actually, you're missing an explanation altogether) -- which leads to repulsive gravity because the final acceleration vector would be [b]pointing away from the gravitational source[/b]. This is precisely why the OP and myself have been continually contradicting you (and others), in spite of your continued insistence. Clearly the OP is confused, so it's probably best to show your work so that we can sort this all out.

[quote name='Olof Hedman' timestamp='1336661168' post='4938991']
Yes, but the object can easily "break free" if the acceleration doesn't increase as closer as you get.
[/quote]

You'd know that's not really true, if you've ever witnessed a shuttle launch. Are you sure you're not confusing acceleration (ie. the gradient of potential energy) with potential energy? I ask this because the tidal force caused by the Earth (ie. the gradient of acceleration) has very little to do with the initial stage of a shuttle launch. In truth, if the acceleration were constant regardless of height, then it would actually be [b]harder [/b]for a shuttle to escape into outer space because it wouldn't catch a break as it climbs higher and higher, like in real life. Edited by taby

Share this post


Link to post
Share on other sites
I obviously was a bit hurried answering yesterday, and probably shouldn't have answered at all.
Though with the vector, I'm just saying that to get a vector from A to B you should do B - A and not the other way around.
He didn't have that wrong really though it seems, he just happened to mix up the words when describing it. Edited by Olof Hedman

Share this post


Link to post
Share on other sites
I didn't say that you were necessarily wrong, just missing a minus sign somewhere. It's not a big deal in the grand scheme of things.

Share this post


Link to post
Share on other sites

This topic is 2046 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this