opengl 为什么这个正方形不在屏幕中间?

gt0wga4j  于 2023-03-02  发布在  其他
关注(0)|答案(1)|浏览(206)

我写了一些代码,期望在屏幕中间看到一个正方形,而不是正方形出现在更高的地方,在屏幕顶部附近的一些宽高比中,稍微向左。

使用其他纵横比:

下面是我的代码的相关部分:

void resize(uint32_t height, uint32_t width){
    glViewport(0, 0, width, height);

    glMatrixMode (GL_PROJECTION); //set the matrix to projection
    glLoadIdentity();
    gluPerspective(60, (GLfloat)width / (GLfloat)height, 1.0, 1000.0);
}

void draw(){
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

    //set up camera
    glLoadIdentity();
    gluLookAt(0,10,0,0,0,0,0.001,0.999,0);

    //draw a square in the center of the screen
    glBegin(GL_TRIANGLE_FAN);
    glColor4f(0,1,1,1);
    glVertex3f(-1,0,-1);
    glVertex3f(-1,0,1);
    glVertex3f(1,0,1);
    glVertex3f(1,0,-1);
    glEnd();

    glPopMatrix();
}

0,0,0不是应该在屏幕中间吗,gluLookAt不是应该把我指定的坐标放在屏幕中间吗?

wgx48brx

wgx48brx1#

更改up矢量的值

gluLookAt(0,10,0,0,0,0,0,0,1);

你的眼睛在正y轴,参考点在中心,up(头部)矢量必须沿着z轴。你在调整大小函数中又犯了一个错误

void resize(uint32_t height, uint32_t width){
glViewport(0, 0, width, height);
.....................
gluPerspective(60, (GLfloat)width / (GLfloat)height, 1.0, 1000.0);
}

变量height存储屏幕宽度,变量width存储屏幕高度,您已经定义了glViewport,并且在gluPerspective中您认为您正在取width乘以height的比率,但实际上您正在取height乘以width的比率,因此出现了问题。请按以下方式编辑代码:

void resize(uint32_t width, uint32_t height){
glViewport(0, 0, width, height);
..................
gluPerspective(60, (GLfloat)width / (GLfloat)height, 1.0, 1000.0);
}

相关问题