简体   繁体   中英

LWJGL draw rect over texture

I use the following to draw the texture quads

tex.bind();
    glTranslatef(x, y, 0);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex2f(0, 0);

    glTexCoord2f(1, 0);
    glVertex2f(width, 0);

    glTexCoord2f(1, 1);
    glVertex2f(width, height);

    glTexCoord2f(0, 1);
    glVertex2f(0, height);

    glEnd();
    glLoadIdentity();

with these configurations:

try {
        Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
        Display.create();

    } catch (LWJGLException e) {
        e.printStackTrace();
    }
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0, WIDTH, HEIGHT, 0, 1, -1);
    glMatrixMode(GL_MODELVIEW);
    GL11.glEnable(GL11.GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    GL11.glDisable(GL11.GL_DEPTH_TEST);
    GL11.glDisable(GL11.GL_LIGHTING);
    GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    GL11.glClearDepth(1);

however now i want to add a menu to the game by drawing a rect over the screen but when i do so, everything turns red (if i set red as color)

    case MENU:
    GL11.glColor3f(1.0f, 0.0f, 0.0f);
    glRectf(50, 50, 50, 50);

Two things:

  1. Whenever you draw using color instead of textures, make sure to disable GL_TEXTURE_2D by calling glDisable(GL_TEXTURE_2D); before the rendering call (in your case before case MENU: ). But don't forget to enable it again as soon as you're finished and ready to draw the texture once again (in your case, call glEnable(GL_TEXTURE_2D); after glRectf() ). This might not be the reason for the problem that you're experiencing, but it will become a problem later.

  2. The reason as to why everything turns red, is because whenever you render a texture, the currently bound color affects what color components are rendered from the texture . Every pixel in the texture that you're drawing is composed of 3 or 4 values. Red , Green , Blue and possibly an Alpha channel. Since you bind the color to red, and you do not change it before you draw the texture, OpenGL only draws the red component of each pixel within your texture. Thus, the Red component will be ranging from 0-1 in your texture, and the Green and Blue values will be staying at a constant 0. To fix this, simply call glColor3f(1, 1, 1); After rendering the red rectangle. This will set the rendering color back to white (default) and therefore OpenGL will successfully draw all 3 color components of your texture pixels.

I hope that I've been clear and that this helps.

Good luck! :)

//SK

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