Search code examples
javaopengllwjgl

glTranslatef not moving with z axis


I write app which draw a rectangle on screen. I want to move this rectangle on z axis but it isn't working. It disappears. I don`t know how to repair that.

Code:

package game;


import org.lwjgl.opengl.GL;

import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;

public class Main {

    public static void main(String[] args) {
        glfwInit();
        System.out.println("Hello World!");
        long  window = glfwCreateWindow(1280   ,720,"Title",0,0);

        glfwMakeContextCurrent(window);
        glfwSwapInterval(1);
        GL.createCapabilities();

        ///////////////////////////////
        glTranslatef(0,0,5);
        ///////////////////////////////


        while(!glfwWindowShouldClose(window)){
            glfwPollEvents();
            glBegin(GL_QUADS);
                glVertex2f(-0.5f,0.5f);
                glVertex2f(-0.5f,-0.5f);
                glVertex2f(0.5f,-0.5f);
                glVertex2f(0.5f,0.5f);
            glEnd();
            System.out.println(z);
            glfwSwapBuffers(window);
        }
        System.exit(0 );
    }
}


Solution

  • By default, only things inside the cube with x,y,z coordinates from -1 to 1 are shown. Because of the glTranslatef at the beginning of your code, you're effectively rendering a square at the coordinates

    (-0.5f,0.5f,5), (-0.5f,-0.5f,5), (0.5f,-0.5f,5), (0.5f,0.5f,5)

    This lies outside of the cube, therefore it isn't shown.

    To change the coordinates in which things are rendered, I recommend looking into glOrtho and glFrustum. With glFrustum you'll also be able to see things in perspective 3D.