五角星的画法:
首先,根据余弦定理列方程,计算五角星的中心到顶点的距离 a(假设五角星对应正五边形的边长为.0)
a = 1 / (2-2cos(72Pi/180));
然后,根据正弦和余弦的定义,计算 B 的 x坐标 bx和 y 坐标 by,以及 C 的y 坐标(假设五角星的中心在坐标原点)
bx = a * cos(18 * Pi/180);
by = a * sin(18 * Pi/180);
cy = -a * cos(18 * Pi/180);
五个点的坐标就可以通过以上四个量和一些常数简单的表示出来,也可以直接给出坐标
令t=0,每次加0.01,可以计算每次五角星变换后的新坐标,x1 = -(1 - t) * 0.5 - t * 0.3;一直重复循环,即可将五角星的变换绘制出来。
代码如下:
#include<Gl/glut.h>
#include <iostream>
#include <Windows.h>
using namespace std;
GLdouble t = 0.01;
GLdouble x1 = -0.5;
GLdouble y11 = 0.3;
GLdouble x2 = 0;
GLdouble y2 = 0.5;
GLdouble x3 = 0.5;
GLdouble y3 = 0.3;
GLdouble x4 = 0.3;
GLdouble y4 = -0.3;
GLdouble x5 = -0.3;
GLdouble y5 = -0.3;
bool count1 = 1;
bool count2 = 0;
void display(void)
{
glLoadIdentity();//恢复初始坐标系
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glColor4f(1, 1, 1, 0);
glPushMatrix();
glBegin(GL_LINE_LOOP); //绘制从第一个顶点到最后一个顶点依次相连的一组线段,然后最后一个顶点和第一个顶点相连,
//第n和n + 1个顶点定义了线段n,绘制n条线段。
glVertex2f(x1, y11);
glVertex2f(x2, y2);
glVertex2f(x3, y3);
glVertex2f(x4, y4);
glVertex2f(x5, y5);
glEnd();
glPopMatrix();
glutSwapBuffers(); // 交换缓冲区
}
void move(int c)
{
if (count1)
{
x1 = -(1 - t) * 0.5 - t * 0.3;
y11 = (1 - t)* 0.3 - t * 0.3;
x3 = (1 - t)*0.5 + t * 0.3;
y3 = (1 - t)*0.3 - t * 0.3;
x4 = (1 - t)*0.3 - t * 0.5;
y4 = -(1 - t)*0.3 + t * 0.3;
x5 = -(1 - t)*0.3 + t * 0.5;
y5 = -(1 - t)*0.3 + t * 0.3;
t = t + 0.01;
cout << t << endl;
if (y5 >= 0.3) {
count1 = 0;
count2 = 1;
}
}
if (count2)
{
x1 = -(1 - t) * 0.5 - t * 0.3;
y11 = (1 - t)* 0.3 - t * 0.3;
x3 = (1 - t)*0.5 + t * 0.3;
y3 = (1 - t)*0.3 - t * 0.3;
x4 = (1 - t)*0.3 - t * 0.5;
y4 = -(1 - t)*0.3 + t * 0.3;
x5 = -(1 - t)*0.3 + t * 0.5;
y5 = -(1 - t)*0.3 + t * 0.3;
t = t - 0.01;
if (y5 <= -0.3) {
count1 = 1;
count2 = 0;
}
}
display();
glutTimerFunc(33, move, 1);
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv); //初始化GLUT
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);//双缓冲区窗口,默认颜色模式
glutInitWindowPosition(100, 100);//确定窗口位置,距离屏幕左边和上边的像素数,
glutInitWindowSize(600, 600);//窗口的宽度和高度
glutCreateWindow("bianhuan");//创建窗口
glutDisplayFunc(&display); //函数负责渲染,调用该函数
glutTimerFunc(33, move, 1); //每隔33毫秒调用一次move()函数
glutMainLoop(); //持续显示,当窗口改变会重新绘制图形
return 0;
}
效果图: