I use a java.awt.Rectangle to represent the visible area of the game world.
Rectangle camera = new Rectangle(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
To make the camera follow the player, I recalculate the location of the camera during the render step of the game, based on the player’s current location. In my game, I want the player to be in the middle of the screen, which means that the camera’s (x, y) location is half a screen above and to the left of the player’s centre point. In code, it looks something like this:
Point pos = player.getCentre();
Point cameraOffset = new Point(pos.x - (camera.width/2)), pos.y - (camera.height/2));
camera.setLocation(cameraOffset);
Your version will be a little different from this, since you want the player to be rendered at (800, 500), rather than in the middle of the screen.
When I’m rendering entities to the screen, I only render them if they are inside the visible area of the game world. Each entity’s image (represented by a rectangle again) must be offset by the camera’s location. The code looks something like this:
Rectangle imageRectangle = entity.getImageRectangle();
if (imageRectangle.intersects(camera) {
entity.render(g, (imageRectangle.x - camera.x), (imageRectangle.y - camera.y));
}
If you want to reuse the camera code in other games, you might want to make it a seperate class. You could add code to:
- Allow the camera to follow entities other than the player.
- Control how quickly the camera follows the entity.
- Control the position the followed entity is rendered to the screen, etc…
I’m sure you get the picture!