Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)) {
                pos.getX() + Display.getDisplayMode().getWidth(), 
                pos.getY() + Display.getDisplayMode().getHeight(), 

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.

share|improve this question
I'm not sure why it's problem for you? just put limits on the values you pass to the glOrtho function. – Ali.S Jul 6 '11 at 21:41
The problem is, that if I reach a left limit of the screen the camera stop moving. Ok, that's fine, but it doesn't move upwards :/ And when I recover the camera again, it jumps to the character causing an ugly effect... – Puyover Jul 6 '11 at 21:49
up vote 4 down vote accepted

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


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();

            cameraPosX + Display.getDisplayMode().getWidth(), 
            cameraPosY + Display.getDisplayMode().getHeight(), 


this code always update the camera, but clamps the camera position in x and/or y

share|improve this answer
Thank you very much!! Seriously I had getting mad with this >.<U I have tested your code and works perfect. Now I only have to limit the right and down boundaries, but that's easy with your example. Thank you again =D – Puyover Jul 6 '11 at 22:29

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.