I'm working on a game in Java, and I'm having some trouble with finding the correct camera position. I've already made a Rectangle that shows exactly where I want the camera to be, and at what scale:
However, whenever I actually try to adjust the camera so it fits with the rectangle, I get weird results. The camera goes in weird places when I get to a point where the scale isn't 1: (The blue rectangle shouldn't be visible in the above gif, because that's where the camera's edges should be.) Right now I have a camera class, where I set the position with:
x=-((leftX+Math.abs(leftX-rightX)/2)-Main.WINDOW_WIDTH/2/scale);
y=-((topY+Math.abs(topY-bottomY)/2)-Main.WINDOW_HEIGHT/2/scale);
Where leftX
, rightX
, topY
, and bottomY
are the topmost, rightmost, topmost, and bottommost points of the rectangle. Those two lines of code are where the problem lies. I simply need to figure out where to move the camera based on the scale.
For translating and scaling, I have this:
g.translate(cam.getX(), cam.getY());
g.scale(cam.scale, cam.scale);
//Render in-game objects
g.translate(-cam.getX(), -cam.getY());
g.scale(1/cam.scale,1/cam.scale);
What I'm asking is, how can I move the camera so that it's perfectly aligned with the rectangle?