Camera Calculation

Hey guys!

At the moment one of my calculations got me stuck.
For the scrolling part I use:


public float getX() {
		float x = player.getX() - size.getX() / 2;
		float maxWidth = (bounds.getWidth() + (size.getX() / 2)) / 2;

		if (x < bounds.getX())
			x = bounds.getX();
		if (x > maxWidth)
			x = maxWidth;

		return x;
}

public float getY() {
		float y = player.getY() - size.getY() / 2;
		float maxHeight = (bounds.getHeight() + (size.getY() / 2)) / 2;

		if (y < bounds.getY())
			y = bounds.getY();
		if (y > maxHeight)
			y = maxHeight;

		return y;
}

getX() and getY() are both offsets I use for everything to scroll.
Now I’m struggling with the camera limit. For getX() the maxWidth calculation works perfectly fine. So I thought that I could use the getX() calculation for the getY() calculation as well. But no, it doesn’t work. It stops too early with scrolling. The max Camera Y I’m having right now is 1792. The max Camera X is 1920.
I’ve tried alot of things but can’t get this to work… Could anyone help me with this one?

Thanks in advance!

Github link:
https://github.com/Desmaster/Nemesis/blob/master/src/nl/tdegroot/games/nemesis/Camera.java

Anyone?

Alright, after doing some guess work on what you’re looking to accomplish. It seems like you’re trying to stop the camera when it reaches the border by taking half the screen width or height from your defined border.

Going with this assumption, if you’re passing 1920 as your screen width, then your screen height should be 1080.
So I think your camera Y should be 1080 instead of 1792, unless you have some sort of weird resolution.

The map is 3200 * 3200 pixels. The camera Y should actually be higher than 1792…
Plus, I don’t know why it doesn’t work for getY while it does for getX

I see, you’re saying the result is 1792 and not a value you’re using to determine camera position.

Alright, after doing a bit of back solving, it looks like your viewport (window size) is 1280x768.
So now we can start plugging some values into your calculations.

Scanning through your logic, it appears the max values are causing the problems. So let’s run the values through and see what happens.

Max Width
(3200 + (1280/2)) /2
(3200 + 640) /2
3840/2 = 1920

Max Height
(3200 + (768/2)) /2
(3200 + 384) /2
(3584)/2 = 1792

From the above, it appears the way you’re calculating the max limits is the error.
The reason it’s working with the width is because 3200 - 1920 = 1280. This means you’re using the edge of the screen as the camera position instead of the center.
So in sticking with that coordinate system, you should just be subtracting the viewport x and y from the map size to find your limits.

To make sure I didn’t derive something incorrectly from your code, I suggest plugging in 2432 for the maxHeight value as a test.

Thank you very much for pointing this out! :slight_smile:
I got ideas for a new camera class, gonna work a bit more with offset.

Thanks! :smiley: