Texture atlas for 2D game

What is the proper way to do a texture atlas for a 2D game?

I have read that you can just load in your atlas, calculate a ratio or map position based on the width / height of the atlas, and then in your render function use
glTexCoord2d(x, y)

Example



//Map caulation (upper left corner calculation)
// atlas width / atlus height : the size of the atlas in pixels
// imageColCountX / imageRowCountY : The number of sprites in the atlas based on row / columns
// spriteMaxWidthLocal / spriteMaxHeightLocal : the end pixel location of the sprite you wish to use

double spriteLoationX =  (atlasWidth / imageColCountX) / spriteMaxWidthLocal;
double spriteLoationY =  (atlasHeight / imageRowCountY) / spriteMaxHeightLocal;

//Upper left
glTexCoord2d(spriteLoationX, spriteLoationY);
glVertex2d(player.viewX, player.viewY);

/*
     Other positions of the quad and etc ...
*/

Is there a better way?

edit: fixed inconstant variable names in example code

I did not quite understand what you did, but this should be correct


vec2 spritePosition; //i.e. the position of the first(left bottom) pixel of the sprite you want to use
vec2 spriteSize;
vec2 atlasSize;

vec2 relativeSize = spriteSize / atlasSize;
vec2 relativePosition = spritePosition / atlasSize;

vec2 LB = relativePosition;                      //left bottom
vec2 RB = vec2(LB.x+relativeSize.x, LB.y); //right bottom
//... and so on for each corner

btw there are tools out there to create texture atlasses out from a bundle of pictures for you.
like from nvidia, libgdx has a CLI, and mine super automatic one :slight_smile:

We seem to be the same, I just started from the top left. Also thanks for the heads up on the atlas programs!

But is that the way I should be going about it? Using / changing glTexCoord2d’s parameters?