http://en.wikipedia.org/wiki/Newton's_law_of_universal_gravitation
along with F=ma of course. It all appears to work correctly, except that I can't achieve an actual orbit. I've gotten plenty of close calls, but in the end the minor stars slingshot around the major stars and end up flinging off into space. I logged some of the accelerations on the bodies that are being slingshot around and found that what appears to be happening (obviously) is that they are picking up acceleration on their way around the star, and can't be slowed down in a reasonable time. The values for their accelerations usually become steady around 1/10^-7 units per second (I'm just using pixels as it is in 2D) and VERRRRRY SLOWWWLY start to turn around and head back toward the major star(s). I have a feeling that this would eventually perform a complete orbit, but it would probably take me years of waiting to see it happen. I'm wondering if maybe I'm doing something wrong or leaving a factor out that contributes to the gravitational pull so that stars can orbit in a more observable manner. Here is the code I'm using for the two major functions dealing with this every frame:
//updates a body's internal statevoid Body::update(float delta) { m_velocity.x += (m_force.x * delta) / (double)m_mass; m_velocity.y += (m_force.y * delta) / (double)m_mass; m_visual.Move(m_velocity.x * delta, m_velocity.y * delta); m_location.x += m_velocity.x * delta; m_location.y += m_velocity.y * delta;}//calculate and apply the force due to gravity void Body::applyPull(Body& otherBody) { double forceOfPull = (GRAVITY_CONSTANT)*(double)(otherBody.getMass()*m_mass); auto dist = this->distanceFrom(otherBody); float forceAngle = std::atan2(dist.y, dist.x); forceOfPull /= (dist.x * dist.x + dist.y * dist.y); double forceX = forceOfPull * std::cos(forceAngle); double forceY = forceOfPull * std::sin(forceAngle); //this can be sped up if needed, we dont actually need to get the angle as we have the ratio otherBody.addImpulse(forceX, forceY);}
EDIT: Okay, I started zeroing my m_force vector at the end of each update() call so that the objects didn't GAIN force each frame and now I'm getting orbits finally which makes me very happy. I'm still very interested in what people may have to recommend me changing / adding to this model so far.
So, anyone have any ideas what I can do to improve this? I know there's a LOT more that can be factored in, and many equations that deal with this sort of thing, but I wanted to start simple so if there's a quick recommendation that will help me solve my issue I would appreciate it.
[Edited by - ChugginWindex on November 20, 2010 2:59:51 PM]