You should start thinking in the "texture space" where the coordinates are in the range [0, 1].
So if you have a sprite sheet:
class SpriteSheet { int spriteWidth, spriteHeight; int texWidth, texHeight; int tex; public: SpriteSheet(int t, int tW, int tH, int sW, int sH) : tex(t), texWidth(tW), texHeight(tH), spriteWidth(sW), spriteHeight(sH) {} void drawSprite(float posX, float posY, int frameIndex); };
All you have to do is send the vertices and vertices of the texture in OpenGL:
void SpriteSheet::drawSprite(float posX, float posY, int frameIndex) { const float verts[] = { posX, posY, posX + spriteWidth, posY, posX + spriteWidth, posY + spriteHeight, posX, posY + spriteHeight }; const float tw = float(spriteWidth) / texWidth; const float th = float(spriteHeight) / texHeight; const int numPerRow = texWidth / spriteWidth; const float tx = (frameIndex % numPerRow) * tw; const float ty = (frameIndex / numPerRow + 1) * th; const float texVerts[] = { tx, ty, tx + tw, ty, tx + tw, ty + th, tx, ty + th };
source share