I can rotate a 3D object, but it doesn’t seem to work for a 2D one.
I’d like to rotate my moveable (via arrows) square for 90 degrees right (rotation center: a center of a square). I’ve come up with a following code:
class CSquare : public CObject {
SPoint pnta; //left top corner of a square
uint16 len; //length
bool bFill, bRotate; //filled? rotating?
GLubyte color[4]; //filling color
float angle; //rotate for this
public:
CSquare();
CSquare(const CSquare &sqr);
CSquare(SPoint &a, uint16 l, bool fill = false);
CSquare(uint16 x, uint16 y, uint16 l, bool fill = false);
void draw();
void toggleRotate();
void setColor(GLubyte r, GLubyte g, GLubyte b, GLubyte a);
void setPoint(uint16 x, uint16 y);
SPoint getPoint();
uint16 getPosX();
uint16 getPosY();
uint16 getLength();
};
void CSquare::draw() {
glPushMatrix();
if (bRotate)
if (++angle < 360.0f)
{
glTranslatef(pnta.nX + len/2, pnta.nY + len/2, 0);
glRotatef(90, 0, 0, 1);
}
else angle = 0.0f;
if (bFill == true) glBegin(GL_QUADS);
else glBegin(GL_LINE_LOOP);
glColor4ubv(color);
glVertex2i(pnta.nX, pnta.nY);
glColor4ub(255, 255, 0, 0); //temporary to visualise rotation effect
glVertex2i(pnta.nX + len, pnta.nY);
glColor4ub(0, 255, 0, 0);
glVertex2i(pnta.nX + len, pnta.nY + len);
glColor4ub(0, 0, 255, 0);
glVertex2i(pnta.nX, pnta.nY + len);
glEnd();
glPopMatrix();
}
My code works to some extent: it does rotate the object but not with a center in a desired point.
PS. I can upload full application if you need it (Visual Studio 2010 Project, uses FreeGLUT and SDL).
I’m going to assume that you’re not actually rotating by a fixed angle:
glRotatef(90, 0, 0, 1);If that’s not a transcription error, you should fix that first.That said, rotation always happens around the origin. You draw your shape at
(pnta.nX, pnta.nY). It seems that you want to rotate around the shape’s center. To do that, you have to first move that point to the origin. Then perform the rotation, then move the point back where you want it:We often model objects with their geometry centered around the origin by default. That way, we can simply rotate the object and then translate its reference point to where we want it.