Compute texture coordinates for a single tile with a texture atlas in OpenGL

I am trying to use a texture atlas in a game program that I write in C # / OpenGl with the OpenTK library.

I uploaded my texture atlas as a texture in OpenGL (size 256x256), and each fragment is 32x32.

To display the first plate of the atlas, I used this code:

GL.Begin(BeginMode.Quads);
GL.TexCoord2(0, 0); GL.Vertex2(0, 0);
GL.TexCoord2(0.125f, 0); GL.Vertex2((32 * zoom), 0);
GL.TexCoord2(0.125f, 0.125f); GL.Vertex2((32 * zoom), (32 * zoom));
GL.TexCoord2(0, 0.125f); GL.Vertex2(0, (32 * zoom));
GL.End();

0.125 was calculated by dividing 1/8, 8 by the number of tiles in the row / column.

I have no idea how to calculate the coordinates of the second tile in this way! I tried using 0.125 and 0.25 instead of 0 and 0.125 respectively, but that does nothing. I assume you are not allowed to use a value greater than zero for the (EDIT) first (0) texture coordinates?

If someone can help or provide a better way to do this, it will be very appreciated!

+3
3
  • "* zoom". gl.scale(, , 1) gl.begin.
  • 8x8 :

    GL.Scale(zoom*32,zoom*32,1);
    GL.Begin(BeginMode.Quads);
    for (int i=0; i<8; i++)
    for (int j=0; j<8; j++)
    {
    var x = i/8.0; // texture scale
    var y = j/8.0;
    GL.TexCoord2(x, y); GL.Vertex2(i, j);
    GL.TexCoord2(x+0.125f, y); GL.Vertex2(i+1, j);
    GL.TexCoord2(x+0.125f, y+0.125f); GL.Vertex2(i+1, j+1);
    GL.TexCoord2(x, y+0.125f); GL.Vertex2(i, j+1);
    }
    GL.End();
    GL.Scale(1.0/(zoom*32),1.0/(zoom*32),1); // unzoom

+1

:

int col = 0;
int row = 0;
float tex_w = 256;
float tex_h = 256;
float tile_w = 32;
float tile_h = 32;
float w_factor = tile_w / tex_w;
float h_factor = tile_h / tex_h;

float x_tex_beg = w_factor*(col+0);
float x_tex_end = w_factor*(col+1);
float y_tex_beg = h_factor*(row+0);
float y_tex_end = h_factor*(row+1);
+2

0 1. , , 32x32, 0.125fx0.125f. , 256/8 = 32. , 32/256.

( , ), ( 0.125f) x. :

GL.TexCoord2(0.125f, 0); GL.Vertex2(0, 0);
GL.TexCoord2(0.25f, 0); GL.Vertex2((32 * zoom), 0);
GL.TexCoord2(0.25f, 0.125f); GL.Vertex2((32 * zoom), (32 * zoom));
GL.TexCoord2(0.125f, 0.125f); GL.Vertex2(0, (32 * zoom));
0

Source: https://habr.com/ru/post/1779667/


All Articles