Archive for demo

planetary gravity demo

Posted in game programming with tags , , , , , , , on January 20, 2008 by brandonman

I played around with some planetary gravity. One of my game ideas I’ve had sitting around is a space based Galaxy that is online. I decided to play around and do some work with gravity. I have a small planet orbiting a sun. There are no textures, but  the orbit is nice. I start by initializing some different variables.

float r;
float dx;
float dy;
float sunx=0;
float sunz=0;
float F;
float M1;
float M2;
float ax;
float ay;
float G=-5;
GLfloat z=-500.0f;   // Depth Into The Screen
GLfloat xpos = -20.0f;
GLfloat zpos = -20.0f;
float vx=.35;
float vy=-.22;

Now I set my masses.

   M1=1; //planet
   M2=332946; //sun

Then I do some math calculations and draw.

 glTranslatef(0,0,z);
dx = xpos-sunx; 
dy = zpos-sunz;
r = sqrt(dx*dx + dy*dy);
F = G*M1*M2/(r*r);
ax = G*M1*dx/(r*r*r);
ay = G*M1*dy/(r*r*r);
vx+=ax;
vy+=ay;
   glColor3f(1.0f,1.0f,0.0f);
   auxSolidSphere(5.0f);
   xpos+=vx;
   zpos+=vy;
   glTranslatef(xpos,zpos,0.0f);
   glColor3f(0.0f,0.4f,1.0f);
   auxSolidSphere(1.0f);
dx is the distance on the x axis, and dy is the distance on the y axis (2D). The other equations are kepler’s law. This is the law of planetary motion created by Johanas? Kepler in the 15 or 1600’s. Then, I move the planet by the velocity and draw. The files I’m linking too are the EXE, the devC++ project file, and the C++ source. This is made in opengl. Just extract these files with Winrar, Winzip, etc and either run the exe or open the project and look at the source and play with it. If you use it in a game, I won’t care, but I’d be honored for you to tell me my source was used.

 http://myfreefilehosting.com/f/47d4a9a79e_0.02MB

NOTE: my source may not be very optimized, but it works. I can’t be held responsible for any problems it may cause. Don’t use it as a guide to learn a programming style! Mine might not be that great.