- Home /
How to reposition camera so that given plane point is in given screen position?
I have a x*z plane (at 0,0,0) and a camera pointing at it, in 60 degrees (and FoW of 60), at changing distance from the plane. Camera can move around, but its angle and relative position to screen (except for y/z according to distance) is static; so, if it now points to world point (0,0,0) and I want it to point to (2,0,2), I simply translate it by (2,0,2)
The problem: I need a function that takes a world coordinate "A" (x,0,z) and viewport position "V" (vx,vz) and returns coordinate where the camera needs to be moved so that after the camera translate, world coordinate "A" is in viewport position "V". If "V" is (0.5,05), this is like normal camera targeting operation, but because of the 3D projection, translation from screen position (0.5,0.1) to (0.5,0.3) is different camera move than from (0.5,0.7) to (0.5,0.9) and so on.
Apparently this is some basic mathematic formula but the details fail me - seems like a common problem (any draggable map in perspective camera) so there must be some (semi-)ready solution in Unity..?
A draggable map in perspective does not have to use the calculation you are asking for. Rather than the solution you are looking for, can you describe the problem you are trying to solve?
Answer by robertbu · Apr 17, 2013 at 02:51 PM
I'm not sure of the problem you are trying to solve, but in general I'd use raycast and perhaps Unity's mathematical Plane class. So given a viewport coordinagte, I can construct a ray using Camera.ViewportToRay(). If my surface has a collider, I can use Physics.Raycast() to cast into the scene. If I don't have a collider, I'd use a mathematical plane at the position of the surface and use the Plane.Raycast() to get the point. Given that you are at a constant 'Y' value, you then can compare the world position of the hit against the position you want at that position. This will give you the delta to move the camera.
You can also play this "game" in reverse if need be. You could construct a plane parallel to the surface that passes through the 'Y' value of the camera. You can then raycast from any point on the surface to this plane.
Your answer
Follow this Question
Related Questions
WorldToViewportPoint and WorldToScreenPoint give wrong positions when VR is enabled 1 Answer
WorldToScreenPoint, wrapping around when outside screen. 1 Answer
How can I accurately convert a Game Object's position to a sub Canvas/Rect screen position? 0 Answers
Calculation behind camera.WorldToScreenPoint 2 Answers
Adjusting returned WorldToScreenPoint for perspective angled camera 4 Answers