简体   繁体   中英

I want to rotate a sprite around its center in LWJGL

No question here has been able to help. I want to rotate a sprite, a quad with a texture, around its center in LWJGL.

Here's my code, currently, it rotates around some other center.

public void draw(int x, int y, int rot) {

// store the current model matrix glPushMatrix();

    // bind to the appropriate texture for this sprite
    texture.bind();

    // translate to the right location and prepare to draw
    glTranslatef(x, y, 0);
            glRotatef(rot,0f,0f,1f);
    // draw a quad textured to match the sprite
    glBegin(GL_QUADS);
    {
    texture.bind(); // or GL11.glBind(texture.getTextureID());

    glBegin(GL_QUADS);
        glTexCoord2f(0,0);
        glVertex2f(100,100);
        glTexCoord2f(1,0);
        glVertex2f(100+texture.getTextureWidth()*2,100);
        glTexCoord2f(1,1);
        glVertex2f(100+texture.getTextureWidth()*2,100+texture.getTextureHeight()*2);
        glTexCoord2f(0,1);
        glVertex2f(100,100+texture.getTextureHeight()*2);
    glEnd();
    }
    glEnd();

    // restore the model view matrix to prevent contamination
    glPopMatrix();
}

Rotating 2d sprite around their center (or any offset point, really) means translating the point you want to rotate around to the origin of your window. If it is the middle of your sprite this means translating the sprite to the point:
-sprite.width/2 , -sprite.height/2
Envision the sprite being "drawn" with one quarter in the screen region and three quarters out of the screen region at this point. Now is the time to rotate it, it will still rotate around the origin, but that happens to also be the middle of the sprite now. Finally, translate the sprite back to where you want it to be on screen.
On a side note, I don't see why people comment his way is deprecated. It is completely irrelevant to the question and there are situations where one wouldn't want to use the newer functionalties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM