An interesting simulation. Thanks for sharing your code - which though not quite working, didn't take much to get going.
mik2718 is correct about treating the other quantities as 2-d vectors. I played around with your code and replaced the Asteroid velocity with xvelocity and yvelocity.
I'm not sure whether this was necessary, or simply my preference, I assigned initial random values (using your existing figures) to these velocity components, which meant there was no longer a need for lines 24-26 in your code above.
For my own purposes, I added a variable and keyboard detection to allow me to adjust the overall speed, this meant the "delta" value needed to be a double rather than an int. I also reduced the default star mass considerably to about 2000.
Also, I found the dots hard to see, so I changed the drawing to use a small polygon (hexagon or octagon) - my first attempt used a triangle but that looked ugly.
Here's some of my code (which may contain trivial changes as well as useful ones):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
Asteroid::Asteroid()
{
using std::cos;
using std::sin;
x = (rand() % 10000) - 5000;
y = (rand() % 10000) - 5000;
mass = (rand() % 200) + 2;
randDir = (rand() % 360) * 0.0174532925;
randVel = (((rand() % 20) + 2) + 0.01) / 500.0;
xvelocity = cos(randDir) * randVel;
yvelocity = sin(randDir) * randVel;
}
void Asteroid::Calculate(double delta)
{
// Calculate Gravity
using std::atan2;
using std::sqrt;
using std::cos;
using std::sin;
double direction = atan2(y, x);
double distance = sqrt((x*x)+(y*y));
double force = ((mass * STAR_MASS)/(distance*distance));
double acceleration = force / mass;
double xacceleration = - acceleration * cos(direction);
double yacceleration = - acceleration * sin(direction);
xvelocity += xacceleration / 64.0;
yvelocity += yacceleration / 64.0;
x += xvelocity * delta;
y += yvelocity * delta;
}
void Asteroid::Draw()
{
glBegin(GL_POLYGON);
glColor3d(((double)mass)/17, ((double)mass)/20, ((double)mass)/22);
glVertex2f(x+ 0.0 , y+ 4.000 );
glVertex2f(x+ 2.8284, y+ 2.8284);
glVertex2f(x+ 4.0 , y+ -0.0 );
glVertex2f(x+ 2.8284, y+ -2.8284);
glVertex2f(x+ 0.000 , y+ -4.000 );
glVertex2f(x+ -2.8284, y+ -2.8284);
glVertex2f(x+ -4.000 , y+ 0.000 );
glVertex2f(x+ -2.8284, y+ 2.8284);
glEnd();
}
|
It would be interesting to add code so that each object exerts a gravitational effect upon all the other asteroids, I may play with that as a separate version.