Domanda

I'm using the following function for drawing a polygon:

void DrawFigure(tNo *iniList)
{
    glClear(GL_COLOR_BUFFER_BIT);

    glBegin(GL_LINE_LOOP);
        // Run through a linked list and create the points.
        for(tNo *p = iniList->prox; p != NULL; p = p->prox)
            glVertex2f(p->x, p->y);
    glEnd();

    glFlush();
}

I know about glRotatef(angle, 0.0f, 0.0f, 1.0f) and it really works properly, but since I have a linked list to store the coordinates I'd like to rotate point by point and then redisplay the figure.

Currently, I'm trying to rotate them around z-axis with

void RotateFigure(tNo *iniList, float angle)
{
    /* Rotation (assuming origin as reference):
     * x' = x.cos(Θ) - y.sin(Θ)
     * y' = x.sin(Θ) + y.cos(Θ)
     */

    for(tNo *p = iniList->prox; p != NULL; p = p->prox)
    {
        float oldX = p->x, oldY = p->y;
        p->x = oldX * cos(angle) - oldY * sin(angle);
        p->y = oldX * sin(angle) + oldY * cos(angle);
    }

    glutPostRedisplay();
}

but there's a huge difference between glRotatef's rotation and this one (not only due to floating-point imprecisions).

Am I missing anything? Isn't there a better approach for rotating the points manually?

È stato utile?

Soluzione

glRotatef assumes that the angle is in degrees. sin and cos assumes it to be in radians. You can adapt your function as follows:

void RotateFigure(tNo *iniList, float angle)
{
    float radians = angle * 3.1415926f / 180.0f; 
    float sine = sin(radians);
    float cosine = cos(radians);        

    for(tNo *p = iniList->prox; p != NULL; p = p->prox)
    {
        float oldX = p->x, oldY = p->y;
        p->x = oldX * cosine - oldY * sine;
        p->y = oldX * sine + oldY * cosine;
    }

    glutPostRedisplay();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top