简体   繁体   中英

Issue with rendering a cube with LWJGL and OpenGL

I've been trying to render a cube and all I'm getting are some weirdly colored squares. The tutorial I'm following says to change the z value in glTranslatef at the beginning of the while loop, but after following that I don't see anything.

private void loop() {
    float rquad = 0;

    GL.createCapabilities();

    while ( !glfwWindowShouldClose(window) ) {
        GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);

        GL11.glLoadIdentity();
        GL11.glTranslatef(0.0f, 0.0f, 0.0f);
        GL11.glRotatef(45f, 0.4f, 0.98f, 0.1f);
        RenderCube();
        // Render end here
        glfwSwapBuffers(window); // swap the color buffers
        glfwPollEvents();

        //Update control variables
        rquad += 0.03;
    }
}

public void RenderCube() {
    GL11.glBegin(GL_QUADS);
    GL11.glColor3f(0.0f, 1.0f, 0.0f);
    GL11.glVertex3f(1.0f, 1.0f, -1.0f);
    GL11.glVertex3f(-1.0f, 1.0f, -1.0f);
    GL11.glVertex3f(-1.0f, 1.0f, 1.0f);
    GL11.glVertex3f(1.0f, 1.0f, 1.0f);
    GL11.glColor3f(1.0f, 0.5f, 0.0f);
    GL11.glVertex3f(1.0f, -1.0f, 1.0f);
    GL11.glVertex3f(-1.0f, -1.0f, 1.0f);
    GL11.glVertex3f(-1.0f, -1.0f, -1.0f);
    GL11.glVertex3f(1.0f, -1.0f, -1.0f);
    GL11.glColor3f(1.0f, 0.0f, 0.0f);
    GL11.glVertex3f(1.0f, 1.0f, 1.0f);
    GL11.glVertex3f(-1.0f, 1.0f, 1.0f);
    GL11.glVertex3f(-1.0f, -1.0f, 1.0f);
    GL11.glVertex3f(1.0f, -1.0f, 1.0f);
    GL11.glColor3f(1.0f, 1.0f, 0.0f);
    GL11.glVertex3f(1.0f, -1.0f, -1.0f);
    GL11.glVertex3f(-1.0f, -1.0f, -1.0f);
    GL11.glVertex3f(-1.0f, 1.0f, -1.0f);
    GL11.glVertex3f(0.1f, 1.0f, -1.0f);
    GL11.glColor3f(0.0f, 0.0f, 1.0f);
    GL11.glVertex3f(-1.0f, 1.0f, 1.0f);
    GL11.glVertex3f(-1.0f, 1.0f, -1.0f);
    GL11.glVertex3f(-1.0f, -1.0f, -1.0f);
    GL11.glVertex3f(-1.0f, -1.0f, 0.1f);
    GL11.glColor3f(1.0f, 0.0f, 1.0f);
    GL11.glVertex3f(1.0f, 1.0f, -1.0f);
    GL11.glVertex3f(1.0f, 1.0f, 1.0f);
    GL11.glVertex3f(1.0f, -1.0f, 1.0f);
    GL11.glVertex3f(1.0f, -1.0f, -1.0f);
    GL11.glEnd();
}

I tried to change the translation values. Is there a simple way to move the cube forward so the camera can see it?

You have to setup a perspective projection matrix with glFrustum . Also see Viewing frustum .

GL11.glMatrixMode(GL.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10.0);

GL11.glMatrixMode(GL.GL_MODELVIEW);
GL11.glLoadIdentity();
GL11.glTranslatef(0.0f, 0.0f, -3.0f);
GL11.glRotatef(45f, 0.5f, 1.0f, 0.0f);

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