Thursday, December 29, 2016

How to add a scrolling camera to a 2D Java game?


I am attempting to create a game where the camera follows the player, always making sure the player is in the center of the screen. How would I go about this? This game is a 2D Java game, made with no engine.


I found an opensource game demonstrating what I want but I cannot work out how to add that to my game. The game is here, if you need it.



Thanks



Answer



First, you need to define the size of the viewport (the camera resolution), for simplicity, let's assume the camera viewport is the size of the screen, we have a 800*600 screen.


Next, you need to define the maximum and minimum offsets of your camera. Assuming you have a world with a size of 1600*1200, the maximum offset would be 800 on X and 600 on Y and 0 on both axis for the minimum offsets. The general formulas to determine the offsets is:


offsetMaxX = WORLD_SIZE_X - VIEWPORT_SIZE_X
offsetMaxY = WORLD_SIZE_Y - VIEWPORT_SIZE_Y
offsetMinX = 0
offsetMinY = 0

Now, over frames, you need to calculate the actual position of the camera. A position that would make the player being centered on the screen. The position need to be calculated relatively to the player position.



camX = playerX - VIEWPORT_SIZE_X / 2
camY = playerY - VIEWPORT_SIZE_Y / 2

Don't forget to check if the camera position do not exceed the maximum and minimum offsets.


if camX > offsetMaxX:
camX = offsetMaxX
else if camX < offsetMinX:
camX = offsetMinX
if camY > offsetMaxY:
camY = offsetMaxY

else if camY < offsetMinY:
camY = offsetMinY

Now that you know the position of the camera, you will to translate the world to this position. When you open a plain window and start drawing stuffs, the area you see start at 0,0. To create the illusion of a camera following the player, you will need to set your drawing area position (the screen in your example) to the camera position.


I don't know what framework/engine you are using but the easiest way to do it is to translate the whole graphic context by the opposite of the current offsets. You will need to know how to access your graphic context and apply a translation to it.


In slick2d, it could look like this:


public void render(..., Graphics g) {
g.translate(-cam.x, -cam.y)
//render the rest of your game
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...