gpt4 book ai didi

c - 翻译单个对象opengl

转载 作者:行者123 更新时间:2023-11-30 15:04:52 25 4
gpt4 key购买 nike

我正在编写代码来绘制图形 Correct output

但是我的代码给出了

My output

如您所见,中间的圆圈丢失了。

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
#include <math.h>

float width, height, r = 0.3, change = 0;

void draw(float tx, float ty)
{
glBegin(GL_LINE_LOOP);
for(int i = 1; i <= 1200; i++)
{
float x1, y1, theta;

theta = (2 * 3.14159 * i) / 1200;
x1 = r * cosf(theta) * height / width;
y1 = r * sinf(theta);

glVertex3f(x1 , y1 ,0);
}

glEnd();
glTranslatef(tx, ty, 0);
}

void display()
{
float p[6][2];
int j = 0;

if (change == 0)
change = 1;
else if (change == 1)
change = 0;

width = glutGet(GLUT_WINDOW_WIDTH);
height = glutGet(GLUT_WINDOW_HEIGHT) ;

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0f, 0.0f, 0.0f);

glMatrixMode(GL_MODELVIEW);
glBegin(GL_LINE_LOOP);

for(int i = 1; i <= 1200; i++)
{
float theta, x1, y1;

theta = (2 * 3.14159 * i) / 1200;
x1 = r * cosf(theta) * height / width;
y1 = r * sinf(theta);

glVertex3f(x1, y1, 0);

if (i == 100 | i == 300 | i == 500 | i == 700 | i == 900 | i == 1100)
{
if(change == 0){
p[j][0] = x1;
p[j][1] = y1;
j++;
}
}

}
glEnd();

for(int i=0;i<6 && change == 0;i++){
draw(p[i][0],p[i][1]);
}
glutSwapBuffers();
}

void main(int argc,char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(700,500);
glutCreateWindow("circles");
glutDisplayFunc(display);
glutMainLoop();
}

问题是当我在绘图函数中翻译第一个圆时,绘制的中心圆也被翻译到与其他圆合并的点。我的疑问是如何仅翻译一个圆而不是我尝试使用推和翻译来翻译的中心圆弹出矩阵,但它不起作用。谢谢。

最佳答案

glTranslatef() 通过附加翻译来更改当前矩阵。所以你的翻译只会不断积累。由于前两个圆之间没有变换,因此它们将出现在相同的位置。您的程序基本上执行以下操作:

Draw Circle
draw()
Draw Circle
Move up, right (p[0])
draw()
Draw Circle
Move up (p[1])
draw()
Draw Circle
Move up left (p[2])
...

如果你想要绝对定位,你必须重置之间的转换。这可以通过glLoadIdentity() 或矩阵堆栈来完成。并且一定要在设置变换后进行绘制。

我想你知道,但无论如何,有一点提醒:整个矩阵堆栈功能在现代 OpenGL 中已被弃用,你需要自己管理矩阵。我想,当你这样做时,一切都会变得更加清晰。所以我不确定是否有充分的理由尝试理解矩阵堆栈功能的接口(interface)。

如果您想将每个圆圈放置在特定位置,您可以执行如下操作:

void drawCircle()
{
glBegin(GL_LINE_LOOP);
for(int i = 1; i <= 1200; i++)
{
float x1, y1, theta;

theta = (2 * 3.14159 * i) / 1200;
x1 = r * cosf(theta) * height / width;
y1 = r * sinf(theta);

glVertex3f(x1 , y1 ,0);
}
glEnd();
}

void display()
{
// ...
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0f, 0.0f, 0.0f);

glMatrixMode(GL_MODELVIEW);
drawCircle();

for(int i = 0; i < 6; ++i)
{
float angle = M_PI / 3 * i;
float tx = r * sin(angle);
float ty = r * cos(angle);
glPushMatrix(); //save the current matrix
glTranslatef(tx, ty, 0); //move to the desired location
drawCircle();
glPopMatrix(); //restore the old matrix
}
glutSwapBuffers();
}

关于c - 翻译单个对象opengl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40116984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com