#### Archived

This topic is now archived and is closed to further replies.

# How do you simulate gravity?

## Recommended Posts

[removed] [Edited by - DevLiquidKnight on February 14, 2007 9:21:39 AM]

##### Share on other sites
Hey,

You just add a velocity vector to you models and increase that with the gravity (9.8m/sec) or your own values

for example:

struct strMyObject {
Vector Pos, Vec;
}

strMyObject Player;

LOOP ->:
Player.Vec.y -= GRAVITY/Framespersec (or just a constant value)

Player.Pos += Vec;

So each frames you add the velocity vector to the players possision to make him accelerate down if nothing is stopping him
(like a floor =

<- LOOP

##### Share on other sites
To elaborate on the AP's response, gravity is a force acting between all objects that have mass. I'll assume for the time being that you want to simulate gravity as it would be felt on the surface of a planet. Let's stick with Earth, since it's nice and easy to relate to.

First, take Newton's First Law:
F = M*a             (1)

Force = Mass * Acceleration

The Gravitational force between two objects is proportional to their masses and inversely proprtional to the square of the separation between them, so that
    G M1 M2F = -------                    (2)      R2

G is the gravitational constant and is equal to 6.672*10-11N m2 kg-2

If you hold one mass (M1) constant, say that of the Earth, then the acceleration that the other mass will undergo, relative to the first mass, is given by combining (1) and (2) to give

    G M1a = -------                    (2)      R2

Substituting in the radius of the Earth (around 6,400 km on average) and the Mass of the Earth (about 5.98*1024 kg) gives an acceleration around 9.8 m s-2.

This is the same acceleration that all bodies undergo at the surface of the Earth. The Force that each body undergoes though is different and is given by F = 9.8 * mass of the body.

Since you know the acceleration of the body, you can work out it's vertical velocity (which is independant of the horizontal velocity) by integrating the acceleration over a fixed time interval, since acceleration is the first derivative of velocity with respect to time. You need to know the starting velocity to do this, since
v(t+dt) = v(t) + integraltt+dt a dt

Furthermore, if you know the position of the object at time t then you can work out its position at time t+dt by integrating the velocity. The result is that for any object near the surface of the Earth, you get the following equations for the height of the object and it's velocity:

s(t+dt) = s(t) + 1/2a*dt2
v(t+dt) = v(t) + a*dt

So if you know a (which you set yourself), the initial height, s(t), and the initial velocity, v(t) m/s (down... negative means up) then you can work out where the object is some time later!

I hope this explains the solution for you.

Good luck,

Timkin

[edited by - Timkin on July 29, 2002 11:36:28 PM]

##### Share on other sites
i have an extremley simple way of simulating gravity, just make an mz variable for your object. every frame, add the gravity variable to mz. and every frame, add mz to z, so that way, it accelerates down until it hits something, then make mz = 0 and only add gravity if bOnGround is false or something

##### Share on other sites
quote:
Original post by Timkin

    G M1a = -------                    (2)      R2

Hey,

I''m just having a problem with this formula: the problem of it is that the acceleration isn''t constant here, and if I calculate physics in a space game every frame, I have to assume that the acceleration is constant during the 1/85th of a second this frame takes, and while this may seem only a small problem, the results of it are dramatic and the physics get more than 100% inaccurate. Do you have an idea how to calculate exactly what happened during one frame, knowing that not only the magnitude but also the direction of the gravity is changing during the time of one frame?

##### Share on other sites
coming across one problem i simulated gravity and now when i walk on the platforms i made i get stuck so i tried to make it subtract 1 from the y variable when he is on a platform so he could move side to side and it causes the guy to bounce up and down really fast

[edited by - DevLiquidKnight on July 30, 2002 8:35:10 PM]

##### Share on other sites
quote:
Original post by Lode
I''m just having a problem with this formula: the problem of it is that the acceleration isn''t constant here, and if I calculate physics in a space game every frame, I have to assume that the acceleration is constant during the 1/85th of a second this frame takes, and while this may seem only a small problem, the results of it are dramatic and the physics get more than 100% inaccurate. Do you have an idea how to calculate exactly what happened during one frame, knowing that not only the magnitude but also the direction of the gravity is changing during the time of one frame?

Unless things are travelling quite fast, then 1/85th of a second is a very small time to integrate over. Are you using an Euler integration (which I suspect you are)?. You may want to consider using a predictor-corrector integration scheme.

Good luck,

Timkin

##### Share on other sites
The 1/85th of a second becomes to large to keep it accurate in two cases:
-if the planet has such a big mass that it generates very strong accelerations if you get close to it, but then for example my ship gets an acceleration of 10000000000m/s² at a certain point and in the 1/85th of a second it''s of course suddenly very far away of the planet... so far that it doesn''t get the negative -10000000000m/s² that it should get when it just crossed the planet anymore.
-if I speed up the time of the simulation: if I speed up the simulation with a factor of 1000, the 1/85th of a second becomes like 11.7seconds and that is too long to keep it accurate.

So indeed I should somehow predict where the ship will be after that time... but what kind of predictor-corrector integration scheme should I be looking for?

##### Share on other sites
Okay, I didn''t realise you were talking about such large accelerations. Since you are, you really cannot treat this problem with classical (Newtonian) physics. You need to deal with the simulation from the perspective of the gravitational potential energy and the conversion from this potential energy into kinetic energy (strictly speaking you should be using General Relativity to get things correct, but that''s more trouble than it''s worth!).

Taking the ''energy approach'' will enable you to bring in relativistic effects that limit the speed of the craft to the speed of light. It will also mean that at high velocities, a huge gravitational potential will only impart a small additional velocity.

If you''ve got an introductory college text on physics everything you need to know is in there. If you don''t, then try google... there''s certainly lots of physics stuff around. Failing that, holler here and I''ll write something up for you (I''m a bit flat out at work today otherwise I''d just do it now for you).

Good luck,

Timkin

##### Share on other sites
quote:
Original post by DevLiquidKnight
coming across one problem i simulated gravity and now when i walk on the platforms i made i get stuck so i tried to make it subtract 1 from the y variable when he is on a platform so he could move side to side and it causes the guy to bounce up and down really fast

I think you''re looking for something simpler than what''s being discussed here!

As the player is falling down towards the platform, you need to calculate whether the players current position + the players current (downward) velocity results in collision with the platform.

If this is the case, you need to ''snap'' the player somehow to the platform so that he appears to be standing on it (how easily you accomplish this depends on how you have stored the platform tiles).

Once the player has been re-positioned on the platform, set the y-acceleration (gravity) to zero and then set a flag saying not to start the downward acceleration again until a platform can no longer be detected underneath the player.

(this is only one way to avoid the ''bobbing'' you talk of, but you could use the ''snapping'' part of your code, but it dpeends on how you structure it).

hope this is of some help. I can elaborate if you like.

##### Share on other sites
quote:
Original post by Carrot
I think you''re looking for something simpler than what''s being discussed here!

As the player is falling down towards the platform, you need to calculate whether the players current position + the players current (downward) velocity results in collision with the platform.

Read the poster''s last post. His application is considerably more complex than Super Mario Brothers.

Don''t listen to me. I''ve had too much coffee.

##### Share on other sites
I was just re-reading the posts to make sure I wasn''t misinterpreting your problem... I''m curious as to why the direction of the acceleration it changing! What frame of reference are you performing the calculations in?

You should compute them in the frame of reference of the planet as this will make life a lot easier for you (unless you have several large planets all close by... but then you have the problem of asking yourself HOW do these planets stay close by without crashing into each other!

Cheers,

Timkin

##### Share on other sites
quote:
Original post by DevLiquidKnight
coming across one problem i simulated gravity and now when i walk on the platforms i made i get stuck so i tried to make it subtract 1 from the y variable when he is on a platform so he could move side to side and it causes the guy to bounce up and down really fast

This sounds like Mario to me.

##### Share on other sites
Okay, the problem is that there are actually two questions in this thread. The first asked by DevLiquidKnight, which I answered in my first post... and the second asked by Lode.

If it isn''t obvious which question you are responding to, please point it out. Perhaps quoting the question in question!

Thanks,

Timkin

##### Share on other sites
Woah - I''m not sure he was after the full-on universal gravitation maths.

Gravity is very simple to do:

If your character is at x,y,z
and every frame you add its velocity vx,vy,vz
then simply accelerate it towards the ground by adding a constant to vz every frame. That constant is the acceleration due to gravity. Note that ALL objects accelerate towards the ground at the same rate. It doesn''t make any difference how heavy it is.

Carrot did a good job of describing how to snap the character to the platform.

##### Share on other sites
quote:
Original post by Anonymous Poster
Woah - I''m not sure he was after the full-on universal gravitation maths.

Again, people really should consider which question and answer they''re making comments about. Yep, DevLiquidKnight only needs the basic Newtonian results I gave at the end of my first post. Lode on the other hand is dealing with a different problem, where a simple Euler integration (as you suggest) is insufficient due to the nonlinearities in the problem.

It''s particularly frustrating to hear people disparage other people''s answers because they haven''t taken note of all of the posts in the thread.

Timkin

##### Share on other sites
quote:
Original post by Timkin

Your right, but surely when someone posts a reply it relates to the original poster''s question by default.

I wasn''t intentionally disparaging anyone, I just thought the original poster was looking for a simple discussion on the implementation of gravity in a 2D platformer.

##### Share on other sites

It seems to me that if you simply add the velocity to the position, at higher velocities, like say 100, the player is going to be skipping 100 pixels at each iteration, possibly missing a whole lot of collisions in the process (platforms, projectiles, etc.) Even at lower velocities it seems easy to miss collisions with thin or small objects.

However, this seems a lot easier than moving the player one pixel per iteration and calculating velocity in terms of the amount of time per iteration. I''m just doubtful about how well it works in practice - maybe the velocities never get high enough for it to be a problem?

Thanks in advance if you can clear this up for me.

Derek

##### Share on other sites
quote:
Original post by derekyu
It seems to me that if you simply add the velocity to the position, at higher velocities, like say 100, the player is going to be skipping 100 pixels at each iteration, possibly missing a whole lot of collisions in the process (platforms, projectiles, etc.)

If each platform or NPC has a collision area described by a bounding box (just for simplicity), and the player''s velocity is described by a two-dimensional vector then a simple ''vector/box intersection'' test will catch any collisions.

So basically you need a function that will test the players velocity-vector (located at player''s current position) with the bounding box (which is just four vector/vector tests).

Hope this helps.

##### Share on other sites
quote:
Original post by Carrot
Your right, but surely when someone posts a reply it relates to the original poster''s question by default.

What is it they say about assumption???

quote:
Original post by Carrot
I wasn''t intentionally disparaging anyone

That comment wasn''t aimed specifically at you (and not even generally, although it does apply to everyone)!

Cheers,

Timkin

##### Share on other sites
quote:
Original post by Carrot
If each platform or NPC has a collision area described by a bounding box (just for simplicity), and the player''s velocity is described by a two-dimensional vector then a simple ''vector/box intersection'' test will catch any collisions.

There was an interesting discussion about a month ago about how to deal with collision detection when collision timescales were expected to be less than integration timescales. If anyone is particularly interested there''s probably a link through my profile... or you can do a search.

Cheers,

Timkin

• ### Forum Statistics

• Total Topics
628353
• Total Posts
2982228

• 10
• 9
• 11
• 24
• 11