Frank
Frank

Reputation: 241

Rotate object around another object

I drew two rectangles in my scene, and now I'm trying to rotate one rectangle around the other.

When I press the "Left key" my first rectangle moves in direction to the other, but I don't have the effect of rotate because it is only moving in a straight line in direction of the other rectangle.

How do I change the Z direction of the first rectangle?

tl;dr: It's like a solar system, but I don't understand how can I have the depth effect.

I'm using GLUT and OpenGL.

EDIT: More Info:

This is my current code (function that shows the scene):

void RenderScene(void){
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

    glColor3f(1.0f, 0.0f, 0.0f); 

    glPushMatrix();

    glTranslatef(-70.0f, 0.0f, 0.0f);
    glRectf(-25.0f, 25.0f, 25.0f, -25.0f); 
    glPopMatrix();

    glColor3f(1.0f, 1.0f, 0.0f);

    glPushMatrix();
    glTranslatef(xCor, 0.0f, 0.0f);
    glRectf(-25.0f, 25.0f, 25.0f, -25.0f);
    glPopMatrix();

    glFlush(); 
}

And a image to help:

enter image description here

enter image description here

Upvotes: 0

Views: 364

Answers (2)

user732933
user732933

Reputation: 278

What you want to do is moderately complicated.

The only way I know to locate rectangles in 3-space is to build them using glVertex3f() like this:


glBegin(GL_QUADS);  
    glVertex3f(x0, y0, z0);  
    glVertex3f(x1, y1, z1);
    glVertex3f(x2, y2, z2);  
    glVertex3f(x3, y3, z3);  
glEnd();

Your "solar system" will have to be located in screen coordinates: X->left/right, Y->up/down, Z->into/out of screen. To create the effect of orbiting, you'll have to recalculate all four X and Z for each movement increment.

I also suggest using gluLookAt() if you want to see a different view.

The man page for glPerspective() says that zNear is always positive but you've given it a negative number. I'd leave that line commented out until I saw some orbiting.

HTH.

Upvotes: 1

user1910317
user1910317

Reputation: 21

Please enable depth test to hide objects beyond other objects. Give a high value z vaue for the far object.

glEnable( GL_DEPTH_TEST );
glClear( GL_COLOR_BUFFER_BIT |GL_DEPTH_BUFFER_BIT);

glPushMatrix();

glTranslatef(-70.0f, 0.0f, 0.0f);
glRectf(-25.0f, 25.0f, 25.0f, -25.0f); 
glPopMatrix();

glColor3f(1.0f, 1.0f, 0.0f);

glPushMatrix();
glTranslatef(xCor, 0.0f, 0.0f);
glRectf(-25.0f, 25.0f, 25.0f, -26.0f); // Z value of behind object is set far from eye
glPopMatrix();

Upvotes: 1

Related Questions