# Restricting Camera Movements with OpenGL

I've been programming a game using the Java library LWJGL. I've got a little problem, though. It is a 2D game, and I'm aiming for a game like the original Civilization (I quick Google of "Civilization 1" will show you what I want). So far I have been able to generate a random 64x64 tile world. Each tile is .5f in size, drawn like this:

float size = .5f;

//...

GL11.glTexCoord2f(uvCoords[0][0], uvCoords[0][1]); GL11.glVertex3f(-size, size, 0.0f);
GL11.glTexCoord2f(uvCoords[1][0], uvCoords[1][1]); GL11.glVertex3f( size, size, 0.0f);
GL11.glTexCoord2f(uvCoords[2][0], uvCoords[2][1]); GL11.glVertex3f( size,-size, 0.0f);
GL11.glTexCoord2f(uvCoords[3][0], uvCoords[3][1]); GL11.glVertex3f(-size,-size, 0.0f);


Now, I don't want my camera to be able to leave this 64x64 space and see black. My camera works like this:

GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glOrtho(position.x, position.x + Display.getDisplayMode().getWidth()/zoom, position.y + Display.getDisplayMode().getHeight()/zoom, position.y, -1, 1);
GL11.glMatrixMode(GL11.GL_MODELVIEW);


I am restricting its movements like this:

public void moveForward(float distance)
{
if(position.y <= 0.5f)
{
return;
}
position.y -= distance;
}

public void moveBackward(float distance)
{
if(position.y >= Constants.WORLD_SIZEY - 0.5)
{
return;
}
position.y += distance;
}

public void moveLeft(float distance)
{
if(position.x <= 0.5f)
{
return;
}
position.x -= distance;
}

public void moveRight(float distance)
{
if(position.x >= Constants.WORLD_SIZEX - 0.5)
{
return;
}
position.x += distance;
}


Because the camera's location is the top left corner of the display, it works great for moveForward and moveLeft. However, for moveBackward and moveRight, it moves out of the 64x64 box until the top left corner gets to the edge. How do I prevent this, because I don't know how to get the screens length in the units I am making the tile sizes.

Sorry if this is hard to understand, because I don't know how to explain it myself. That's why I've had so much trouble finding an answer.

Seems to me you want the limit for moveRight to be Constants.WORLD_SIZEX - 0.5 - Display.getDisplayMode().getWidth()/zoom, and similarly for moveBackward.

The coordinates you pass in to glOrtho are the world space locations that will be mapped to the corners of the screen, so you see that when position.x equals the expression I just mentioned, the right edge of the screen will be at Constants.WORLD_SIZEX - 0.5, which (if I understand correctly) should be the right edge of the rightmost column of tiles.

Incidentally, I'd suggest applying the limits like this:

public void moveForward(float distance)
{
position.y -= distance;
position.y = max(position.y, 0.5f);
}


The way you did it will only work correctly if you only move around in steps of 0.5. Any other step size could lead to the camera going a bit beyond the bounds and seeing some black, although never more than half a tile's worth.