# Render specific part of a texture in OpenGL (2D Sprite Sheet)

I've looked at this answer to find out how to render just a part of a texture: C++ Opengl render part of an image

I tried that, but the problem is, this is how I render my texture:

glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(x, y);
glTexCoord2f(1, 0); glVertex2f(x + w, y);
glTexCoord2f(1, 1); glVertex2f(x + w, y + h);
glTexCoord2f(0, 1); glVertex2f(x, y + h);
glEnd();


I tried doing this to render the top left quarter:

glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(x, y);
glTexCoord2f(0.5, 0); glVertex2f(x + w, y);
glTexCoord2f(0.5, 0.5); glVertex2f(x + w, y + h);
glTexCoord2f(0, 0.5); glVertex2f(x, y + h);
glEnd();


But it just totally messes up and makes my texture bigger and cut off. What I want is to just draw a part, like you would on a sprite sheet. I've been messing around with those lines for awhile and I just can't seem to find out how to do what I want.

I've been messing around with this:

// yeah i know this math is crappy and weird but im trying EVERYTHING at this point,
// it draws until the dcw (width) just fine but i cant seem to integrate cx/cy...

double dcw = double(cw) / double(w);
double dch = double(ch) / double(h);

double dcx = double(cx) / double(dcw);
double dcy = double(cy) / double(dch);

std::cout << "dcw:" << dcx << "\n" << "dch:" << dcy << "\n";

//bottom right
glTexCoord2f(0, 0); glVertex2f(cx, cy);
//top right
glTexCoord2f(dcw, 0); glVertex2f(cx + cw, cy);
//top left
glTexCoord2f(dcw, dch); glVertex2f(cx + cw, cy + ch);
//bottom left
glTexCoord2f(0, dch); glVertex2f(cx, cy + ch);

• Well, makes my texture bigger and cut off, isn't that what you want? to draw just one quarter of it? Of course it gets stretched if you draw only a quarter of the texture but on the same-sized quad. – tkausl Jul 27 '15 at 22:57

I don't quite understand what your problem is, since you're not being very specific. But I'll try.

Your code seems fine to me.
glVertex2f() controls where you want to render your quad to the screen. glTexCoord2f() controls what part of the texture you want to apply to the quad.
So obviously if you increase the size of your quad but don't increase the part of the texture you apply to it, it will become stretched.

Well, I finally got it after messing around with the math for awhile I kinda understand it. If anyone wants the code here it is.

double dcx = double(cx) / double(w);
double dcy = double(cy) / double(h);

double dcw = (double(cx)+double(cw)) / double(w);
double dch = (double(cy)+double(ch)) / double(h);


• You should check your math again. -cx+(cx)+x negative cx plus cx equals zero, so -cx+(cx)+x is equal to just x. You do this for every single param. – tkausl Jul 28 '15 at 16:11