OpenGL:如何在指定UV坐标时避免舍入错误

Sir*_*irp 6 c opengl floating-point

我正在使用OpenGL编写2D游戏.当我想将一部分纹理作为精灵blit时,我使用glTexCoord2f(u,v)指定UV坐标,u和v计算如下:

GLfloat u = (GLfloat)xpos_in_texture/(GLfloat)width_of_texture;
GLfloat v = (GLfloat)ypos_in_texture/(GLfloat)height_of_texture;
Run Code Online (Sandbox Code Playgroud)

除非我使用glScale来放大或缩小游戏,否则大部分时间都可以正常工作.然后浮点舍入误差导致一些像素被绘制在纹理内的预期矩形的右侧或下方.

关于这个还能做什么?目前我正在从矩形的右边缘和底边缘减去一个'epsilon'值,它似乎可以工作,但这似乎是一个可怕的kludge.还有更好的解决方案吗?

Jim*_*uck -2

您的 xpos/ypos 必须基于 0 到(宽度或高度)- 1,然后:

GLfloat u = (GLfloat)xpos_in_texture/(GLfloat)(width_of_texture - 1);
GLfloat v = (GLfloat)ypos_in_texture/(GLfloat)(height_of_texture - 1);
Run Code Online (Sandbox Code Playgroud)