Why isn't this a square? LWJGL

五迷三道 提交于 2019-12-01 04:26:30

Using glOrtho(0, 640, 0, 480, 1, -1); constructs a non-square viewport. That means that the rendered output is more than likely going to be skewed if your window is not the same size as your viewport (or at least the same aspect ratio).

Consider the following comparison:

If your viewport is the same size as your window, then it should remain square. I'm using JOGL, but in my resize function, I reshape my viewport to be the new size of my window.

glcanvas.addGLEventListener(new GLEventListener() {
    @Override
    public void reshape(GLAutoDrawable glautodrawable, int x, int y, int width, int height) {
        GL2 gl = glautodrawable.getGL().getGL2();

        gl.glMatrixMode(GL2.GL_PROJECTION);
        gl.glLoadIdentity(); // Resets any previous projection matrices
        gl.glOrtho(0, width, 0, height, 1, -1);
        gl.glMatrixMode(GL2.GL_MODELVIEW);
    }

    ... Other methods

}

To draw a square around the point (x | y) you can calculate the four points that represent the corners of your square.

First you'll need your width to height ratio

float ratio = width / height

I will use a defaultSize for the length of the shortest path from the midpoint to any of the sides.

Then you can calculate four values like so:

float a = x + defaultSize 
float b = ratio * (y + defaultSize) 
float c = x - defaultSize 
float d = ratio * (y - defaultSize)

with which you can represent all four corners to draw your square with. Since GL_SQUAD is deprecated I'll use GL_TRIANGLE.

glBegin(GL_TRIANGLES);
glColor3f(red, green, blue);

// upper left triangle
glVertex2f(a, b);
glVertex2f(c, b);
glVertex2f(c, d);

 // lower right triangle
glVertex2f(a, b);
glVertex2f(c, d);
glVertex2f(a, d);

glEnd();

I don't know if this is the most performant or idiomatic way to do this since I just started exploring LWJGL.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!