我试图制作一个简单的类来加载spritesheets并从中绘制2D纹理。但是,当我尝试渲染其中一个精灵时,它没有正确执行。我要么得到任何东西,要么只得到一些粉红色的点(http://i.imgur.com/qQl0Y5n.png)。有人可以帮我找出问题所在吗?
public enum Art
{
GREEN("misc_1", 7, 5, 27, 10),
BLUE("misc_1", 6, 37, 28, 5),
MAGENTA("misc_1", 19, 68, 28, 6);
private String spritesheet;
private int coordX;
private int coordY;
private int width;
private int height;
Art(String s, int x, int y, int w, int h)
{
this.spritesheet = s;
this.coordX = x;
this.coordY = y;
this.width = w;
this.height = h;
}
public String getSpritesheet()
{
return this.spritesheet;
}
public void render(int x, int y, int w, int h)
{
if (spritesheets.containsKey(this.getSpritesheet()))
{
Texture tex = spritesheets.get(this.getSpritesheet());
if (glGetInteger(GL_TEXTURE_BINDING_2D) != tex.getTextureID())
{
tex.bind();
}
float i = coordX / tex.getWidth();
float j = coordY / tex.getHeight();
float k = (coordX + width) / tex.getWidth();
float l = (coordY + height) / tex.getHeight();
int xx = x + w;
int yy = y + h;
glBegin(GL_QUADS);
glTexCoord2f(i, j);
glVertex2i(x, y);
glTexCoord2f(k, j);
glVertex2i(xx, y);
glTexCoord2f(k, l);
glVertex2i(xx, yy);
glTexCoord2f(i, l);
glVertex2i(x, yy);
glEnd();
}
}
private static boolean isLoaded = false;
public static HashMap<String, Texture> spritesheets = new HashMap<String, Texture>();
public static void loadTextures()
{
if (!isLoaded)
{
try
{
Texture misc_1 = TextureLoader.getTexture("PNG", new FileInputStream("res/misc_1.png"));
spritesheets.put("misc_1", misc_1);
} catch (IOException e)
{
e.printStackTrace();
}
isLoaded = true;
}
}
}
如果有帮助,这就是我的initGL方法:
private void initGL()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 1280, 720, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
编辑:我只需将getWidth()和getHeight()更改为getImageWidth()和getImageHeight(),即可解决问题。
答案 0 :(得分:0)
您没有显示Texture
课程的定义。但我认为getWidth()
和getHeight()
会返回int
个结果。如果是这种情况,那么您在此处遇到问题:
float i = coordX / tex.getWidth();
float j = coordY / tex.getHeight();
coordX
和tex.getWidth()
都是int
类型的值,因此除法将作为整数除法执行。例如,如果coordX
小于tex.getWidth()
,结果将始终为零。
要获得浮点除法,您需要将其中一个值转换为float
:
float i = (float)coordX / tex.getWidth();
float j = (float)coordY / tex.getHeight();
有关详细信息,请参阅此问题:How to make the division of 2 ints produce a float instead of another int?。