I'm trying to make a camera that follows my character and it seems I've managed. However, I don't know how to limit that my camera don't follow me when my character reachs the boundaries of the windows (it's ugly see black spaces beyond my tile map x_x).
So, this is my code:
public class Camera {
public void update(Vector2f spritePos) {
Vector2f pos = new Vector2f(spritePos.getX()-368, spritePos.getY()-268);
if((pos.getX()+368 > 368) && (pos.getY()+268 > 268)) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(pos.getX(),
pos.getX() + Display.getDisplayMode().getWidth(),
pos.getY() + Display.getDisplayMode().getHeight(),
pos.getY(),
-1,
1);
glMatrixMode(GL_MODELVIEW);
}
}
}
I substract 368 to the X position, because I want to place my character at the center of my camera. Same with 268. This is a bad way to archieve this, because my camera "jumps" roughly to the position of my character >.
Thank you very much.
Answer
The problem is the if condition
(pos.getX()+368 > 368) is equal to (pos.getX() > 0) and
(pos.getY()+268 > 268) is equal to (pos.getY() > 0)
then the refactored condition can be
if( ( pos.getX() > 0 ) && ( pos.getY() > 0 ) )
//that means that the camera is only updated if pos is > that 0,0
For example, if pos is -2,0 the condition is false and the camera is not updated. We want that camera follow the character included in this case
then
public void update(Vector2f spritePos) {
Vector2f pos = new Vector2f(spritePos.getX()-368, spritePos.getY()-268);
// new code
float cameraPosX = 0;
float cameraPosY = 0;
cameraPosX = ( pos.getX() < 0 ) ? 0 : pos.getX();
cameraPosY = ( pos.getY() < 0 ) ? 0 : pos.getY();
//
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(cameraPosX,
cameraPosX + Display.getDisplayMode().getWidth(),
cameraPosY + Display.getDisplayMode().getHeight(),
cameraPosY,
-1,
1);
glMatrixMode(GL_MODELVIEW);
}
this code always update the camera, but clamps the camera position in x and/or y
No comments:
Post a Comment