calgorithmbgiturbo-c

Graphics (Rotation in 2D)


I am now trying for 8+ hours to solve this but cant figure it out, please help find whats wrong with my code.

int main() {
    int gd = DETECT, gm;
    float ANGLE = 360/10 * M_PI/180;

    initgraph(&gd, &gm, NULL);
    int cx = getmaxx() / 2;
    int cy = getmaxy() / 2;
    int p[] = {cx-50,cy-150, cx+50,cy-150, cx+50,cy-50, cx-50,cy-50, cx-50,cy-150};

    outtextxy(cx, cy, "*");
    setcolor(G);

    int n, i; 
    for (n = 0; n < 10; n++)
    {
            drawpoly(5, p);
            for (i = 0; i < 10; i+=2)
            {
                    p[i] = p[i]*cos(ANGLE) - p[i+1]*sin(ANGLE) + cx - cx*cos(ANGLE) + cy*sin(ANGLE);
                    p[i+1] = p[i]*sin(ANGLE) + p[i+1]*cos(ANGLE) + cy - cx*sin(ANGLE) - cy*cos(ANGLE);
            }
    }

    getch();
    closegraph();
    return (0);
}

The output

But i need like this.

expected output


Solution

  • Thanks to Paul Ogilvie. I was using p[i] with modified value instead of old one in order for transformation to work. thanks again!

    New code:

    int main() {
        int gd = DETECT, gm;
        float ANGLE = 360/10 * M_PI/180;
    
        initgraph(&gd, &gm, NULL);
        int cx = getmaxx() / 2;
        int cy = getmaxy() / 2;
        int p[] = {cx-50,cy-150, cx+50,cy-150, cx+50,cy-50, cx-50,cy-50, cx-50,cy-150};
    
        outtextxy(cx, cy, "*");
        setcolor(G);
    
        int n, i, save;
        for (n = 0; n < 10; n++)
        {
                drawpoly(5, p);
                for (i = 0; i < 9; i+=2)
                {
                        save = p[i];
                        p[i] = p[i]*cos(ANGLE) - p[i+1]*sin(ANGLE) + cx - cx*cos(ANGLE) + cy*sin(ANGLE);
                        p[i+1] = save*sin(ANGLE) + p[i+1]*cos(ANGLE) + cy - cx*sin(ANGLE) - cy*cos(ANGLE);
                }
        }
    
        getch();
        closegraph();
        return (0);
    }
    

    And output:

    yep