• Create Account

Need scary sound effects or creepy audio loops for your next horror-themed game? Check out Highscore Vol.3 - The Horror Edition in our marketplace. 50 sounds and 10 loops for only \$9.99!

# Help with making a gravity well.

Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

19 replies to this topic

### #1homer_3  Members   -  Reputation: 173

Like
0Likes
Like

Posted 08 May 2012 - 07:24 PM

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


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);


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, 08 May 2012 - 07:25 PM.

### #2Bacterius  Crossbones+   -  Reputation: 5584

Like
0Likes
Like

Posted 08 May 2012 - 08:34 PM

Vector3 gravDir = curGravWellPos - transform.position;
should be
Vector3 gravDir = transform.position - curGravWellPos;
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, 08 May 2012 - 08:35 PM.

"The best comment is a deleted comment."

### #3homer_3  Members   -  Reputation: 173

Like
0Likes
Like

Posted 08 May 2012 - 08:55 PM

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.

### #4jefferytitan  Members   -  Reputation: 1039

Like
1Likes
Like

Posted 09 May 2012 - 12:39 AM

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.

### #5Bacterius  Crossbones+   -  Reputation: 5584

Like
0Likes
Like

Posted 09 May 2012 - 12:58 AM

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.

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.

"The best comment is a deleted comment."

### #6jefferytitan  Members   -  Reputation: 1039

Like
0Likes
Like

Posted 09 May 2012 - 02:22 AM

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.

### #7Olof Hedman  Crossbones+   -  Reputation: 1665

Like
0Likes
Like

Posted 09 May 2012 - 03:09 AM

I thought you subtracted the position of the other guy from yourself to get a vector going from yourself to the other guy.

You have it backwards.

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.

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, 09 May 2012 - 03:10 AM.

### #8h4tt3n  Members   -  Reputation: 719

Like
1Likes
Like

Posted 09 May 2012 - 04:08 AM

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

### #9homer_3  Members   -  Reputation: 173

Like
0Likes
Like

Posted 09 May 2012 - 06:12 AM

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.

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.

I thought you subtracted the position of the other guy from yourself to get a vector going from yourself to the other guy.

You have it backwards.

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.

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.

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

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

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

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?

### #10h4tt3n  Members   -  Reputation: 719

Like
0Likes
Like

Posted 09 May 2012 - 06:29 AM

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?

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

### #11Bacterius  Crossbones+   -  Reputation: 5584

Like
1Likes
Like

Posted 09 May 2012 - 07:34 AM

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

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 .

And anyway, acceleration depends on mass, from . 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 on the Earth, and the Earth exerts a force on you (Newton's third law). Then the acceleration on you is 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 which is, for all practical purposes, zero. If you didn't apply 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.

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.

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, 09 May 2012 - 07:36 AM.

"The best comment is a deleted comment."

### #12taby  Members   -  Reputation: 285

Like
1Likes
Like

Posted 09 May 2012 - 10:28 AM

Not that this matters a whole lot to a lot of people, but a real, physically accurate gravitational field can and does 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. http://en.wikipedia....ional_radiation

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. http://en.wikipedia....i/Bremstrahlung

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.
http://en.wikipedia....Quantum_gravity

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: http://en.wikipedia....Gravityroom.svg

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: http://en.wikipedia....macroscopic.svg

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:

Distance from target to gravitational source:

Unit direction vector pointing from target to gravitational source:

Mass of gravitational source:

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:

Edited by taby, 09 May 2012 - 06:05 PM.

### #13homer_3  Members   -  Reputation: 173

Like
0Likes
Like

Posted 09 May 2012 - 06:16 PM

Thanks to your guys' help I am making progress. My new code looks like


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));


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.

### #14jefferytitan  Members   -  Reputation: 1039

Like
0Likes
Like

Posted 09 May 2012 - 06:32 PM

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.

### #15homer_3  Members   -  Reputation: 173

Like
0Likes
Like

Posted 09 May 2012 - 06:44 PM

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.

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"?

### #16taby  Members   -  Reputation: 285

Like
0Likes
Like

Posted 09 May 2012 - 08:02 PM

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, 09 May 2012 - 11:31 PM.

### #17Olof Hedman  Crossbones+   -  Reputation: 1665

Like
0Likes
Like

Posted 10 May 2012 - 08:46 AM

I thought you subtracted the position of the other guy from yourself to get a vector going from yourself to the other guy.

You have it backwards.

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.

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.

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.

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

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

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

Edited by Olof Hedman, 10 May 2012 - 08:47 AM.

### #18taby  Members   -  Reputation: 285

Like
0Likes
Like

Posted 10 May 2012 - 10:28 AM

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.

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: http://galileo.phys....avPotEnergy.htm

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

If you want to tell the OP to negate the direction vector V, 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 pointing away from the gravitational source. 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.

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

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 harder 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, 10 May 2012 - 11:34 AM.

### #19Olof Hedman  Crossbones+   -  Reputation: 1665

Like
0Likes
Like

Posted 11 May 2012 - 01:52 AM

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, 11 May 2012 - 01:53 AM.

### #20taby  Members   -  Reputation: 285

Like
0Likes
Like

Posted 11 May 2012 - 07:42 AM

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.

Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

PARTNERS