改进代码glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON); for(int i=0;i<n;++i){ glVertex2f(R*float(cos(2*Pi/n*i)),R*float(sin(2*Pi/n*i))); } glEnd();
时间: 2023-05-28 12:08:15 浏览: 44
改进代码如下:
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // 设置背景颜色为黑色
glClear(GL_COLOR_BUFFER_BIT); // 清空颜色缓冲区
glBegin(GL_POLYGON);
for(int i = 0; i < n; i++) {
float x = R * cos(2 * Pi / n * i);
float y = R * sin(2 * Pi / n * i);
glVertex2f(x, y);
}
glEnd();
// 禁用顶点属性数组
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
相关问题
give me an example code for test run the open gl
Sure, here is a simple example code for running OpenGL:
```
#include <GL/glut.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
glFlush();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutCreateWindow("OpenGL Test");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
```
This code creates a window with the title "OpenGL Test" and displays a square in it. You can compile and run this code using an OpenGL-compatible compiler and libraries.
用c语言,opengl,请写出类似下面的程序,做到顺时针旋转二维图形,void rotate() { GLfloat tempX, tempY; for (int i = 0; i < 4; i++) { tempX = vertices[i][0] * cos(theta) - vertices[i][1] * sin(theta); tempY = vertices[i][0] * sin(theta) + vertices[i][1] * cos(theta); vertices[i][0] = tempX; vertices[i][1] = tempY; } glutPostRedisplay(); }
以下是一个使用 C 语言和 OpenGL 库实现二维图形顺时针旋转的示例代码:
```c
#include <GL/glut.h>
#include <math.h>
// 定义一个二维图形(矩形)的顶点坐标
GLfloat vertices[4][2] = {{0, 0}, {0, 1}, {1, 1}, {1, 0}};
// 定义旋转角度(弧度制)
GLfloat theta = M_PI / 2; // 90 度
void rotate() {
GLfloat tempX, tempY;
for (int i = 0; i < 4; i++) {
tempX = vertices[i][0] * cos(theta) - vertices[i][1] * sin(theta);
tempY = vertices[i][0] * sin(theta) + vertices[i][1] * cos(theta);
vertices[i][0] = tempX;
vertices[i][1] = tempY;
}
glutPostRedisplay();
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_POLYGON);
for (int i = 0; i < 4; i++) {
glVertex2fv(vertices[i]);
}
glEnd();
glFlush();
}
void init() {
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-1.0, 2.0, -1.0, 2.0);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("Rotation");
init();
glutDisplayFunc(display);
rotate(); // 在窗口创建后立即进行旋转操作
glutMainLoop();
return 0;
}
```
在上述代码中,首先使用 OpenGL 库定义了一个二维图形的顶点坐标数组 `vertices`,然后定义了旋转角度 `theta`。接着,实现了一个 `rotate()` 函数,该函数将顶点坐标数组 `vertices` 中的每个顶点坐标进行旋转变换。最后,在 `display()` 函数中绘制旋转后的二维图形。
需要注意的是,在上述代码中,我们将旋转操作放在了 `main()` 函数中的 `glutCreateWindow()` 函数之后,这样可以保证窗口创建后立即进行旋转操作。同时,由于我们只需要对一个简单的二维图形进行旋转变换,因此在 `init()` 函数中只进行了简单的投影矩阵设置。如果需要对更复杂的三维图形进行旋转变换,可能需要更复杂的投影矩阵设置。