- #1
RossH
- 75
- 0
Homework Statement
I am making a standard N-body simulation for a computer science class and, for some reason, the objects that I am simulating accelerate past each other, and then engage in spring-like motion, getting closer and then farther apart, etc. Obviously incorrect.
Homework Equations
If you can't read C++, this is how I am calculating the forces (in x-y plane):
1) Calculate distance with Pythagorean theorem
2) set total force on the hypotenuse equal to Gm1m2/r^2
3) Find the distance on x and y-axis between the two bodies
4) The x component of the force is equal to the totalforce*x_distance/hypotenuse length
5) Same for y component
6) Update the x and y components by subtracting the forces found from the total force on the object at this time
Is there anything really obvious wrong with this? I'm not quite sure about the subtraction in step (6), but it seems to work. Bodies push away from each other when I have it as addition; they attract when I have it as subtraction. Anyway, I just can't figure out why mo bodies accelerate past each other and exhibit this strange motion where they refuse to stick together. Any help would be much appreciated.
If you can read C++, the code that I am using to calculate forces between two objects is this (should be pretty self-explanatory code)
for(int i=0; i<bodies.size(); i++) //body being acted upon
{
bodies.setforcex(0); //reset all forces to zero
bodies.setforcey(0);
for(int j=0; j<bodies.size(); j++) //acting body
{
if(i!=j) //update forces
{
double dist=distance(bodies.getxloc() , bodies.getyloc() , bodies[j].getxloc() , bodies[j].getyloc());
if(dist>(bodies.getradius()+bodies[j].getradius())) //basic collision detection: don't do this if the bodies are too close
//prevents asymptotic behavior of the force graph
{
double totalforce=G*bodies.getmass()*bodies[j].getmass()/(dist*dist); //force vector, now I need to split it into x, y components
double diff_x=bodies.getxloc()-bodies[j].getxloc();
double diff_y=bodies.getyloc()-bodies[j].getyloc();
//first solve for x,y components
double x_component=totalforce*(diff_x/dist); //cosine triangle times total force
double y_component=totalforce*(diff_y/dist); //sine triangle times total force
//Now add forces to objects
if(bodies[j].getneg())
{
bodies.setforcex(bodies.getforcex()+x_component);
bodies.setforcey(bodies.getforcey()+y_component);
}
else
{
bodies.setforcex(bodies.getforcex()-x_component);
bodies.setforcey(bodies.getforcey()-y_component);
}
}
}
}
}