# Rotating a polygon around it's center

I have drawn a ship using three lines, and would like to rotate the ship around its axis in opengl, I have tried the following, but the ship translates while rotation!.

void Ship::Draw( )
{
gl::pushMatrices();
gl::translate(Vec2f(-m_Pos.x, -m_Pos.y));
gl::rotate(m_Angle);
gl::translate(Vec2f(m_Pos.x,m_Pos.y));
gl::color(ci::Color(1,0,0));
gl::drawLine(Vec2f(281,70),Vec2f(383,123));
gl::drawLine(Vec2f(310,85),Vec2f(310,160));
gl::drawLine(Vec2f(383,123),Vec2f(281,176));

gl::popMatrices();
m_Angle+=0.2f;
}


To rotate a polygon around its centre like this, you need to draw it around the origin.

Currently you're drawing it off-centre:

gl::drawLine(Vec2f(281,70),Vec2f(383,123));
gl::drawLine(Vec2f(310,85),Vec2f(310,160));
gl::drawLine(Vec2f(383,123),Vec2f(281,176));


What this means is that these points are rotated around (0,0) by your angle m_Angle.

Instead, put equal amounts on either side of (0,0):

gl::drawLine(Vec2f(-43,-52),Vec2f(59,1));
gl::drawLine(Vec2f(-14,-31),Vec2f(-14,38));
gl::drawLine(Vec2f(59,1),Vec2f(-43,54));

• I have tried your code, but the ship is drawn hidden and it is still rotating but translating also and not around the its center – Ahmed Saleh Jul 19 '12 at 21:31
• I forgot to mention - you don't need to un-do the position translation. Remove gl::translate(Vec2f(-m_Pos.x, -m_Pos.y)); as well. – Matt Kemp Jul 19 '12 at 21:35
• it is worked. Could you explain more what was the problem ? and If I want to do the same scenario but with a circle or a rectangle what should I do ? What should I read more into ? OpenGL or 3D Math? – Ahmed Saleh Jul 19 '12 at 21:38
• This answer is correct, but you better do a glLoadIdentity() after pushing the matrix, just in case there is any transformation accumulated before calling Draw(). – Dan Jul 19 '12 at 22:04
• @Dan Would you explain it more ? I didn't get what I'm doing wrong. What should I read more ? – Ahmed Saleh Jul 19 '12 at 22:15

Have you done any other gl::translate before that? What is the state of the GL_MODELVIEW matrix at that time? Take into account that if you have accommulated other transformations then gl::translate(-m_pos.x, -m_pos.y) does not bring you back to the origin. I would call glLoadIdentity() rather then gl::translate(-m_pos.x, -m_pos.y), then you rotate and translate where you want to go.