I have following piece of code, now i want to move the "moon" object in the orbit around "earth". please help!!

#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
int main()
int gd,gm;

settextstyle(DEFAULT_FONT, HORIZ_DIR, 2);
outtextxy(10, 10, "Welcome to Graphics Programming");
outtextxy(10, 30, "My VU-ID is BC123456789");


int Earth_x,Earth_y;
Earth_x=10+390/2;        // This expression calculates the center of the rectangle
Earth_y=60+340/2;        // as we want to draw our Earth in the center.
outtextxy(Earth_x, Earth_y, "Earth");

//Moon orbit

int Moon_x,Moon_y;
Moon_x=Earth_x+100;         //Initial coordinates of Moon
while(1){                   // continuous loop as condition will always be true
outtextxy(Moon_x, Moon_y, "Moon");
// redraw Moon orbit
outtextxy(Moon_x, Moon_y, "Moon");

Use polar coordinate system. Cast Moon's position to polar coordinates by formulas:

r = sqrt( sqr(Moon_x - Earth_x) + sqr(Moon_y - Earth_y) );
phi = atan2( Moon_y - Earth_y, Moon_x - Earth_x );

Then, you can change angle (phi) to move Moon around the center:

phi += angular_speed;

And after that cast changed polar coordinates back to cartesian coordinates:

Moon_x = r * cos( phi )
Moon_y = r * sin( phi )
  • \$\begingroup\$ Good answer. do note that this will only work if the object in question is round \$\endgroup\$ – Timothy Groote Nov 24 '14 at 11:02
  • \$\begingroup\$ What do you mean in "object is round"? You mean orientation (sprite rotation) of object will not be changed? Yes, it's true, but in case Moon orbiting around Earth, orientation should be calculated separately even if Moon is round. \$\endgroup\$ – Kostya Regent Nov 24 '14 at 11:39
  • \$\begingroup\$ What i mean is that OP's wording of the question was wider. (how to move an object around the circumference of another object). Your answer works porfectly for planets, because x=r*cos(phi); y=r*sin(phi) makes you move in (2d) circles, and can even be scaled up to 3d. but imagine trying to move along the circumference of a plank, or a house... \$\endgroup\$ – Timothy Groote Nov 25 '14 at 10:02
  • 2
    \$\begingroup\$ Ah, now I understand what you mean. Question has inconsistent topic. Topic should be "How to move object along circumference of another object's orbit". Because Moon moves along circumference of Earth means that Moon would have 0 height (roll on the surface of Earth). \$\endgroup\$ – Kostya Regent Nov 25 '14 at 11:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.