LWJGL 玩家生命值条位置不正确



我正在使用LWJGL在Java中制作游戏,最近slick_util我正在尝试实现一个将悬停在玩家头顶的健康条。问题是,它没有正确定位。生命条的左下角(OpenGL 开始绘制的位置)始终显示在玩家矩形的右上角,当玩家向 x 或 y 或两者移动时,生命条会沿同一方向远离玩家。我认为这可能是glTranslatef的问题,或者可能是我错过的愚蠢的东西。

播放器的渲染方法:

protected void render() {
        Draw.rect(x, y, 32, 32, tex); //Player texture drawn
        Draw.rect(x, y + 33, 32, 15, 1, 0, 0); //Health bar drawn. x is the same as player's, but y is +33 because I want it to hover on top
    }

抽奖类:

package rpgmain;
import static org.lwjgl.opengl.GL11.*;
import org.newdawn.slick.opengl.*;
/**
 *
 * @author Samsung
 */
public class Draw {
    public static void rect(float x, float y, float width, float height, Texture tex) {
        glEnable(GL_TEXTURE_2D);
        glTranslatef(x, y, 0);        
        glColor4f(1f, 1f, 1f, 1f);
        tex.bind();
        glBegin(GL_QUADS); //Specifies to the program where the drawing code begins. just to keep stuff neat. GL_QUADS specifies the type of shape you're going to be drawing.
        {
            //PNG format for images
            glTexCoord2f(0,1); glVertex2f(0, 0);  //Specify the vertices. 0, 0 is on BOTTOM LEFT CORNER OF SCREEN.
            glTexCoord2f(0,0); glVertex2f(0, height); //2f specifies the number of args we're taking(2) and the type (float)
            glTexCoord2f(1,0); glVertex2f(width, height); 
            glTexCoord2f(1,1); glVertex2f(width, 0);
        }
        glEnd();
        glDisable(GL_TEXTURE_2D);
    }
    public static void rect(float x, float y, float width, float height, float r, float g, float b) {
        glDisable(GL_TEXTURE_2D);
        glTranslatef(x, y, 0);
        glColor3f(r, g, b); 
        glBegin(GL_QUADS); //Specifies to the program where the drawing code begins. just to keep stuff neat. GL_QUADS specifies the type of shape you're going to be drawing.
        {                 
            glVertex2f(0, 0);  //Specify the vertices. 0, 0 is on BOTTOM LEFT CORNER OF SCREEN.
            glVertex2f(0, height); //2f specifies the number of args we're taking(2) and the type (float)
            glVertex2f(width, height);
            glVertex2f(width, 0); 
        }
        glEnd();
        glEnable(GL_TEXTURE_2D);
    }
}

我认为你的问题出在矩阵上。当您调用glTranslatef时,您正在转换OpenGL ModelView矩阵。但是,由于 OpenGL 是基于状态的计算机,因此将保留此转换以供进一步绘制事件使用。第二个矩形将平移两次。您要做的是使用 OpenGL 矩阵堆栈。我将在这里重写其中一个绘制方法:

public static void rect(float x, float y, float width, float height, Texture tex) {
    glEnable(GL_TEXTURE_2D);
    glPushMatrix();
    glTranslatef(x, y, 0);        
    glColor4f(1f, 1f, 1f, 1f);
    tex.bind();
    glBegin(GL_QUADS);
    {
        glTexCoord2f(0,1); glVertex2f(0, 0);
        glTexCoord2f(0,0); glVertex2f(0, height);
        glTexCoord2f(1,0); glVertex2f(width, height); 
        glTexCoord2f(1,1); glVertex2f(width, 0);
    }
    glEnd();
    glPopMatrix();
    glDisable(GL_TEXTURE_2D);
}

行 glPushMatrix() 将在堆栈顶部添加一个新矩阵。从这一点开始的所有转换都将应用于新添加的矩阵。然后,当你调用glPopMatrix()时,矩阵将被丢弃,堆栈将返回到它以前的状态。

最新更新