Domanda

I've been trying to display blocks on screen, each with different textures. I've got the spritesheet set up as well as the code. But I can't manage to get specific coordinates in the spritesheet, I can't display anything else as the first image.

I've got this render function set up:

public static void render(int texture, int blockID) {
    float xPos = (float)blockID;
    float yPos = 0;

    while(xPos > 9) {
        xPos -= 10;
        yPos++;
    }

    glBindTexture(GL_TEXTURE_2D, texture);

    glPushMatrix();
        glBegin(GL_TRIANGLES);
            glTexCoord2f((8f / 160f) * xPos, (8f / 160f) * yPos); glVertex2i(16, 0);
            glTexCoord2f((8f / 160f) * xPos, (8f / 160f) * yPos); glVertex2i(0, 0);
            glTexCoord2f((8f / 160f) * xPos, (8f / 160f) * yPos); glVertex2i(0, 16);

            glTexCoord2f((8f / 160f) * xPos, (8f / 160f) * yPos); glVertex2i(0, 16);
            glTexCoord2f((8f / 160f) * xPos, (8f / 160f) * yPos); glVertex2i(16, 16);
            glTexCoord2f((8f / 160f) * xPos, (8f / 160f) * yPos); glVertex2i(16, 0);
        glEnd();
    glPopMatrix();
}

It decides which texture to take from the blockID, so if the blockID is 1 it takes the second image from the spritesheet, if it's 2 it takes the third image, etc.

But I don't know where I have to multiply the xPos and yPos variables to the glTexCoord2f. I've tried different ways like:

glTexCoord2f(xPos / 128f, 0f / 128f); glVertex2i(16, 0);
glTexCoord2f(0f / 128f, yPos / 128f); glVertex2i(0, 16);

or

glTexCoord2f((0f / 128f) * xPos, 0f / 128f; glVertex2i(16, 0);
glTexCoord2f(0f / 128f, (8f / 128f)) * yPos; glVertex2i(0, 16);

and even

glTexCoord2f(0f / 128f, 0f / 128f); glVertex2i(16 * xPos, 0);
glTexCoord2f(0f / 128f, 8f / 128f); glVertex2i(0, 16 * yPos);

But none worked.

=== EDIT ===

I've almost managed to get it working. But only with odd blockID's. If the blockID is 1 it displays the first texture, but if it's 2 it displays a brownish color (that isn't on my spritesheet) and if the blockID is 3 it displays the second texture on the sheet etc.

È stato utile?

Soluzione

Texture coordinates exist within the range: 0.0f --> 1.0f

You need to calculate how far along (in percentage) the image your sprite is, then feed that into TexCoord as a float.

I think you should be using:

   (8.0f / 128.0f) * xPos             (you should cache the float once it works)

If this does not work, ensure these two things:

  • Hard coded values work (Proving that your texture is loaded and initialised fine)
  • The correct values are being calculated within your render method

Alternatively, don't forget to render your Triangles with glColor(1.0f, 1.0f, 1.0f) to ensure that the rest of your rendering in your application works.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top