Pregunta

So me and a friend are wanting to make a sidescroller but we have come into an issue with the camera. How can we make a camera that will follow the player but not in a hard scrolling but instead a soft scrolling. What I mean by that is that the camera will move only when the player moves to a certain position on the window. We are using java to code this but I think any language could help as long as it shares the same concept.

¿Fue útil?

Solución

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
Same is needed for Y axis.

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 c) {
    g.translate(-cam.x, -cam.y)
    //render the rest of your game
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top