C# XNA Simulate Gravity
I have a question regarding using primitive sha开发者_开发百科pes and simulating a circle to be free falling. How would I go about this? Do I use the formula for gravity?
It depends how detailed you want to be. Newtonian gravity laws dictate an force which has inverse square relationship between two bodies and their distance.
- F is the magnitude of the gravitational force between the two point masses,
- G is the gravitational constant,
- m1 is the mass of the first point mass,
- m2 is the mass of the second point mass, and
- r is the distance between the two point masses.
So if you are simulating large bodies (say a planetary system) you need to apply gravity between each pair of objects.
Obviously, once you know the force you can apply Newton's second law (force=mass*acceleration) to calculate the acceleration you should apply to each body.
On the other end of the simplicity scale, if you have a fixed reference frame with respect to a single very large body (the ground) and multiple small objects, all you really need to do is apply a constant acceleration towards the ground. In this case, (in a vacuum) gravity on earth applies a constant acceleration of 9.81m/s2 to all objects. CodeInChaos gives a good code example of this.
(Of course we now know that Newtonian gravity isn't quite right and it breaks down at very large and very small scales. But that's a bit beyond this answer)
Gravity is just constant acceleration downwards.
Pseudocode:
const Vector3D Gravity=(0, 0, -9.8 m/s^2);
Vector3D Acceleration=Gravity;//insert other forces here
Vector3D Position+=Speed*DeltaT+0.5*Acceleration*DeltaT*DeltaT.
Vector3D Speed+=Acceleration*DeltaT;
You can use a physics engine, like Farseer:
http://roy-t.nl/index.php/2010/09/10/xna-farseer-platformer-physics-tutorial/
Simple version: if your circle has direction and speed then gravity is just a additional direction and speed pointing at the direction you want your gravity to pull.
Even simpler: just move the location of the circle downwards.
After this just fine tune it to fit your purpose with acceleration and setting the speed.
精彩评论