Does anyone have an example of implementing Orbital Mechanics (preferably in XNA)? The code I am currently using is below, but it doesn’t ‘feel right’ when it executes. The object just bends ever so slightly to the planet, and no matter how much I tweak the variables I cant get it to enter an orbit, or even a partial orbit.
shot.Position += shot.Velocity; foreach (Sprite planet in planets) { Vector2 directionToPlanet = (planet.Position - shot.Position); directionToPlanet.Normalize(); float distance = Vector2.DistanceSquared(shot.Position, planet.Position); float gPull = (float)(planet.gravityStrength * (planet.Mass * shot.Mass) / distance) + planet.gravityField; shot.Position += new Vector2(directionToPlanet.X * gPull, directionToPlanet.Y * gPull); }
Edit Marking Mendelt’s answer correct for pointing out that I need to update the velocity, not the position. I also needed to change the calculation of gPull to
float gPull = shot.Mass * planet.Mass / distanceSqr * planet.gStr;
In the last line you’re updating the position of the shot. You should be updating the velocity.
You might want to take a look at the code in this blogpost http://blog.mendeltsiebenga.com/post/Fun-with-planets.aspx No xna, but working orbital mechanics. (although i never got rid of the screen-flicker)