PDA

View Full Version : Rotate only one object in 2D

bobgonr
12-04-2016, 10:47 AM
Hello, I am trying to recreate the classic game Asteroid https://upload.wikimedia.org/wikipedia/en/1/13/Asteroi1.png using OpenGL. So far I have drawn a ship, some text and a test asteroid. I have set up controls such that UP arrow moves the ship forwards, LEFT and RIGHT keys rotate the ship.

2302

The problem lies in the rotation. When I attempt to rotate the ship, everything in the screen rotates as well.

2303

However I only want the ship to move. How can I do this?

Here is my draw function:

void draw() {
glClear(GL_COLOR_BUFFER_BIT); // Clear display window.

myWorld.draw_world();

char *score = {"Score: "};
glRasterPos2f(1, 14);
print_bitmap_string(GLUT_BITMAP_9_BY_15, score);

myWorld.shipType[selection]->rotate(myWorld.shipType[selection]->center[0], myWorld.shipType[selection]->center[1],angle);

glFlush();
}

and the rotation function looks like this:

void Shape2D::rotate(GLfloat rx, GLfloat ry, GLfloat angle){
// rx and ry is the coordinate for the center point of the ship

glTranslatef(rx, ry, 0);
glRotatef(angle, 0., 0., 1.);
glTranslatef(-rx, -ry, 0);
}

myWorld.draw_world just simply draws the ship onto the screen:

void World::draw_world() {
//draw triangle
if (selection == 0) {
shipType[0]->draw();
}
// draw square
else if (selection == 1) {
shipType[1]->draw();
} else if (selection == 2) {
shipType[2]->draw();
}
// draw test asteroid
myAsteroid->draw();
}

Cornix
12-04-2016, 03:16 PM
Push your current matrix, manipulate it with the translatef / rotatef calls, draw the sprite you want to have rotated and then pop the matrix again before drawing the other sprites.