back to main Space page
N-body simulator C++ code
//C++ code snippets for an N-body simulator
//Uses a very simple single-step iterative method.
//In my opinion if you want to write an n-body simulator,
// its best to start with a simple method like this,
// (and change to a better method after you've got everything working).
//Please note this is not a complete program, just the core functions
//The top-level function is SSystem::CalcAll(), it calls all the other functions
//Website: http://www32.brinkster.com/snefru/space
bool SSystem::CalcAll()
{
PullAll();
MoveAll();
return(true);
}
bool SSystem::PullAll()
{
double DistX, DistY, DistZ, Dist, DistSquared;
double GravX, GravY, GravZ, Grav;
//for each permutation of two stars
for(int i=0; iPosX-Body[i]->PosX;
DistY=Body[j]->PosY-Body[i]->PosY;
DistZ=Body[j]->PosZ-Body[i]->PosZ;
DistSquared=DistX*DistX+DistY*DistY+DistZ*DistZ;
Dist=sqrt(DistSquared);
//body i attracts body j
if(Body[i]->MassFlag)
{
Grav=Body[i]->Mass*GravConst/DistSquared;
GravX=Grav*DistX/Dist;
GravY=Grav*DistY/Dist;
GravZ=Grav*DistZ/Dist;
Body[j]->VelX+=GravX*Step;
Body[j]->VelY+=GravY*Step;
Body[j]->VelZ+=GravZ*Step;
}
//body j attracts body i
if(Body[j]->MassFlag)
{
Grav=Body[j]->Mass*GravConst/DistSquared;
GravX=-Grav*DistX/Dist;
GravY=-Grav*DistY/Dist;
GravZ=-Grav*DistZ/Dist;
Body[i]->VelX+=GravX*Step;
Body[i]->VelY+=GravY*Step;
Body[i]->VelZ+=GravZ*Step;
}
}
}
return(true);
}
bool SSystem::MoveAll()
{
for(int i=0; iMove();
return(true);
}
bool SBody::Move()
{
PosX+=VelX*TheSystem->Step;
PosY+=VelY*TheSystem->Step;
PosZ+=VelZ*TheSystem->Step;
return(true);
}
back to main Space page