简体   繁体   中英

LWJGL - Switching from 3D to 2D to render text with NO external librarys

I want to render 2D quads on my screen by switching to a 2D scene then switching back to 3D. I dont want to use any external librarys besides LWJGL.

This is what I got so far:

private static void renderLetter(char c, float x, float y) {
    int character = c+1;
    GL11.glPushMatrix();

    setOrthoOn();

    GL11.glTranslatef(x, y, 0);

    float[] xy = game.getResourceManager().getSpriteSheets().get(fontSheet).getXYForCell(character);
    float cellx = game.getResourceManager().getSpriteSheets().get(fontSheet).getCell_sizeX();
    float celly = game.getResourceManager().getSpriteSheets().get(fontSheet).getCell_sizeY();
    float xx = xy[0];
    float yy = xy[1];

    GL11.glBindTexture(GL11.GL_TEXTURE_2D, game.getResourceManager().getTextures().get(game.getResourceManager().getSpriteSheets().get(fontSheet).getTextureID()));
    GL11.glBegin(GL11.GL_QUADS);
        GL11.glTexCoord2f(xx, yy);
        GL11.glVertex2f(0,0);
        GL11.glTexCoord2f(xx+cellx, yy);
        GL11.glVertex2f(fontSize,0);
        GL11.glTexCoord2f(xx+cellx, yy+celly);
        GL11.glVertex2f(fontSize,fontSize);
        GL11.glTexCoord2f(xx, yy+celly);
        GL11.glVertex2f(0,fontSize);
    GL11.glEnd();
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);      

    setOrthoOff();

    GL11.glPopMatrix();
}

public static void setOrthoOn()
{
    GL11.glDisable(GL11.GL_LIGHTING);
    GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);                
    GL11.glClearDepth(1);
    GL11.glViewport(0,0,1360,768);
    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity();
    GL11.glOrtho(0, 1360, 768, 0, 1, -1);
    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    GL11.glLoadIdentity();
}

public static void setOrthoOff()
{
    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity();
    GLU.gluPerspective(game.getFieldOfView(), 1360f/768f, 0.1f, 1000);
    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    GL11.glLoadIdentity();
    GL11.glEnable(GL11.GL_DEPTH_TEST);
    GL11.glDepthFunc(GL11.GL_LEQUAL);
    GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
}

the first method is to render a letter. what I am trying to do is by calling setOrthoOn switch to 2D rendering then render the quad then call setOrthoOff to switch back to 3D.

This code does nothing for me when I run it.. What am I doing wrong?

This should do it.

Note: some of the code may be extraneous. I'm not very experienced with OpenGL, but this worked for me. I would also recommend you import GL11 staticly. That way you don't have to type "GL11.BlaBlaBla", you can just type "BlaBlaBla".

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