- Home /
Center Object in Viewport
Greetings; I am confronted with a problem that I am unsure of how to solve. I have an orthographic camera with a Y transform of 260 overlooking the scene. It has a rotation of X 25 and Y 50; "zooming in and out" is handled by changing the camera's projection size. This gives the project an isometric effect; moving up and down and zooming in and out works perfectly. However, a feature I'd like to add is the ability to click on an object in the viewport and move the camera accordingly so that the object is centered in the viewport. Getting the position of the object in world space and comparing it to the camera's is seemingly out of the question due to how the camera is set up. I know that I can get the object's viewport as opposed to its world position, but I'm unsure of what to do with it as far as accomplishing my goal is concerned. Any advice would be greatly appreciated.
Edit: I need the camera to slowly move to the target as opposed to snapping to it.
Answer by Philipp · Dec 10, 2012 at 05:37 PM
Your camera's transform has a Vector3 named forward. The camera position you want is the target position, plus this forward vector, times a scalar chosen so that the result is at y=260. In code: camPos = target.transform.position + camera.transform.forward * (260-target.transform.position.y)/camera.transform.forward.y;
Alternatively, you could parent the camera to an empty GameObject, set the camera's local transform to what you have now, and then just move the GameObject around.
Thank you very much. However, when I try to perform a Vector3.Slerp(camera.transform.position, camPos, Time.time) operation in the Update so that the camera slowly moves to the new position, ins$$anonymous$$d of abruptly jumping to the position, the camera does not seem to behave correctly. Ins$$anonymous$$d, the scene begins to look "twitchy" and the distance from the camera to the ground isn't correct. What might be causing my problem?