简体   繁体   中英

Resizing window skewes display (OpenGL)

I am making a program that bounces balls of the edge of its window, but I'm having issues with the bounds getting skewed.

If I set the initial resolution to a square window,

int windowWidth = 600;

int windowHeight = 600;

it works fine. As soon as I reshape the window, the bounds on the window get skewed.

When it's square, it looks like this: 在此处输入图片说明

When I stretch it by its width, it looks like this: 在此处输入图片说明

When I stretch it by its height, it looks like this: 在此处输入图片说明

Basically I'm not able to resize the window without skewing the bounds of the window.

This is the code for my reshape function:

void reshape(GLsizei weight, GLsizei height)  
{ 
    if (height == 0) height = 1;               // To prevent divide by 0 
    GLfloat aspect = (GLfloat)weight / height; // Get aspect ratio 

    // Set the viewport to cover the entire window 
    glViewport(0, 0, weight, height); 

    // Adjust the aspect ratio of clipping area to match the viewport 
    glMatrixMode(GL_PROJECTION); // Select the Projection matrix 
    glLoadIdentity();            // Reset 

    for (int i = 0; i < numOfBalls; i++) 
    { 
        if (weight <= height)  
        { 
            balls[i].xLeft   = -1.0; 
            balls[i].xRight  = 1.0; 
            balls[i].yBottom = -1.0 / aspect; 
            balls[i].yTop    = 1.0 / aspect; 
        }  
        else 
        { 
            balls[i].xLeft   = -1.0 * aspect; 
            balls[i].xRight  = 1.0 * aspect; 
            balls[i]. yBottom = -1.0; 
            balls[i]. yTop    = 1.0; 
        } 
        gluOrtho2D(balls[i].xLeft, balls[i].xRight, balls[i].yBottom, balls[i].yTop); 
        balls[i].xPosMin = balls[i].xLeft + balls[i].ballRadius; 
        balls[i].xPosMax = balls[i].xRight - balls[i].ballRadius; 
        balls[i].yPosMin = balls[i].yBottom + balls[i].ballRadius; 
        balls[i].yPosMax = balls[i].yTop - balls[i].ballRadius; 
    } 

    glMatrixMode(GL_MODELVIEW); // Select the model-view matrix 
    glLoadIdentity();           // Reset 
} 

*Note: I can post more code if needed...

Try cut this from your loop:

gluOrtho2D(balls[i].xLeft, balls[i].xRight, balls[i].yBottom, balls[i].yTop);

and define your orthographic matrix once.

I think whenever your loop execute, you multiply a new matrix with previously inserted matrix in GL.

The produced orthographic matrix by GL is this:

在此处输入图片说明

Now when you set width: 800 and height: 600 your aspect ratio will be 1.33 and matrix for first loop will be:

在此处输入图片说明

Now by each loop, GL will multiply new matrix with previous matrix and coordinates will get closer by multiply each by 0.75.

(Also i am not sure)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM