Pregunta

I'm using OpenGL. For my tiles, I'm using a display list and I'm just using immediate more for my player (for now). When I move the player, I want to center him in the center of the window, but allow him to jump around on the y axis and not have the camera follow him. But the problem is, is that I can't figure out how to center the player in the viewport! Here is the player update method:

public void update() {
    if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
        World.scrollx -= Constants.scrollSpeed;
        setCurrentSprite(Sprite.PLAYER_RIGHT);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
        World.scrollx += Constants.scrollSpeed;
        setCurrentSprite(Sprite.PLAYER_LEFT);
    }
    move((Constants.WIDTH) / 2  + -World.scrollx, getY());
}

World.scrollx and World.scrolly are variables that I increase/decrease to move the tiles. move() is just a method that sets the player position, nothing else. I render the player at his current coordinates like this:

public void render() {
    glBegin(GL_QUADS);
    Shape.renderSprite(getX(), getY(), getCurrentSprite());
    glEnd();
}

Shape.renderSprite is this:

public static void renderSprite(float x, float y, Sprite sprite){
    glTexCoord2f(sprite.x, sprite.y + Spritesheet.tiles.uniformSize());
    glVertex2f(x, y);
    glTexCoord2f(sprite.x + Spritesheet.tiles.uniformSize() , sprite.y + Spritesheet.tiles.uniformSize());
    glVertex2f(x + Constants.PLAYER_WIDTH, y);
    glTexCoord2f(sprite.x + Spritesheet.tiles.uniformSize(), sprite.y);
    glVertex2f(x + Constants.PLAYER_WIDTH, y + Constants.PLAYER_HEIGHT);
    glTexCoord2f(sprite.x, sprite.y);
    glVertex2f(x, y + Constants.PLAYER_HEIGHT);
}

Pretty simple, I just render the quad at the current player's position. This is how I actually render everything:

public void render(float scrollx, float scrolly) {
    Spritesheet.tiles.bind();
    glPushMatrix();
    glTranslatef(scrollx, scrolly, 0);
    glCallList(tileID);
    glPopMatrix();
    player.render();
}

This is the part I'm confused on. I translate the tiles according to the scrollx and scrolly variables, and then I render the player at his current position. But the player moves faster than the tiles scroll, and he can escape out the side of the screen! How do I center the player with moving tiles?

Thanks for any help!

¿Fue útil?

Solución

If you want the player to be fixed at the center of the screen, then World.scrollx and World.scrolly should be derived from the player position, not changed independently from it. Your update should look something like (conceptually)

void update {
    getPlayerInput()
    updatePlayerPosition();
    updateWorldCoordinatesFromPlayerPosition();
} 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top