1
\$\begingroup\$

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: enter image description here

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: enter image description here (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?

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

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Pikalek Aug 18 '18 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.