# Aligning Camera to Rectangle

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?

• you want the camera to follow the player ?
– ZEE
Feb 8 '15 at 21:02
• can u provide more code or just put your hole game in github that ur can contribute to it
– ZEE
Feb 8 '15 at 21:08

I managed to figure it out. The answer was actually extremely simple, and I was overthinking it. I just changed

x=-((leftX+Math.abs(leftX-rightX)/2)-Main.WINDOW_WIDTH/2/scale);
y=-((topY+Math.abs(topY-bottomY)/2)-Main.WINDOW_HEIGHT/2/scale);


to

x=-rect.x*scale;
y=-rect.y*scale;


where rect is that blue rectangle shown in the original post.

• Glad to see that you found a solution! Don't forget to mark it as accepted - it helps others who may run into the same or similar problems. Aug 18 '18 at 19:33