- Home /
Camera zoom while keeping an off-center object at the same screen co-ordinates
Camera zoom whiloe keeping an offcenter object at the same screen co-ordinates.
Im doing a zoom by dragging on the highligted red ball below.
How do I get the ball to stay at it's screen coords while the rest of the view zooms in?
Thanks in advance
James
Nope a perspective camera as there is some 3d effects going on too...
Are you zoo$$anonymous$$g the camera by changing the field of view or by moving the camera towards the subject?
Currently by moving the camera... though not adverse to using FOV
Answer by robertbu · Feb 15, 2013 at 07:54 PM
I've not got time right now to write the test code, but here is the idea:
Use Camera.main.WorldToViewportPoint() before making the move (or even in Start()) to get the position in viewport space of the object.
Move the camera in for the zoom.
Get the new Viewport coordinates for the new position of the object.
Using the new distance between the camera and the board, calculate the world positions for the two viewport positions using Camera.ViewportToWorldPoint();
Subtract the two to get how far to translate the board or the camera.
Got a chance to test it in code:
public class ZoomWithOffCenterObject : $$anonymous$$onoBehaviour {
public GameObject goTrack;
private Vector3 v3ZoomFactor = new Vector3(0.0f, 0.0f, 0.05f);
void Update () {
if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.UpArrow))
ZoomCamera (true);
if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.DownArrow))
ZoomCamera (false);
}
private void ZoomCamera(bool bIn) {
Vector3 v3OrgPos = Camera.main.WorldToViewportPoint(goTrack.transform.position);
if (bIn)
transform.Translate (v3ZoomFactor);
else
transform.Translate (-v3ZoomFactor);
v3OrgPos.z = $$anonymous$$athf.Abs (Camera.main.transform.position.z - goTrack.transform.position.z);
v3OrgPos = Camera.main.ViewportToWorldPoint(v3OrgPos);
transform.Translate (goTrack.transform.position - v3OrgPos);
}
}
Looks really good, and works in a clean scene...
However my camera tracks in Y and I can't for the life of me get this to handle that...
Any ideas?
The code above looks down the Z axis, so Y is up. Are you saying your camera is looking down the Y axis at the XZ plane?