1
\$\begingroup\$

Currently I have 2 cameras, one for viewing the 3D objects (Perspective), and the other camera to view 2D objects (Orthographic).
(Also, the view of the camera never intercepts each other.)

I am trying to display a 2D object based on the position of a 3D object, like so: Image of what I am trying to achieve

What I have is the respective 2D and 3D Camera, as well as the Vector3 position of the 3D GameObject.

What I have tried:

public Vector2 Convert3DPositionTo2DPosition(Camera camera3D, Vector3 position3D, Camera camera2D) {
    var tempPos = camera3D.WorldToViewportPoint(position3D);

    return camera2D.ViewportToWorldPoint(tempPos);
}

The only problem is that the returned position is not completely aligned with the 3D position.
Which results in this kind of results: Image of expected and actual result

Also, I have made sure that both the 3D and 2D object have their pivot point are set correctly in the center, but it still does not work as intended.

(I am currently using Unity 2019.1.14f1)

\$\endgroup\$
0
\$\begingroup\$

Instead of ViewportToWorldPoint use WorldToScreenPoint

https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html

Oh yeah, and call the function on your 2D camera :D

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Can you explain why going via screen coordinates would have a different result than going via viewport coordinates? \$\endgroup\$ – DMGregory Aug 27 '19 at 13:52
  • \$\begingroup\$ Unfortunately it did not work; The position is now way off from expected. Could you show the final result of the code, in case I missed out on anything. (P.S: would also be nice if you gave explanations like what DMGregory mentioned) \$\endgroup\$ – WQYeo Aug 28 '19 at 1:25
  • \$\begingroup\$ Looking again at your "Convert3DPositionTo2DPosition" function i notice you are converting your 3D position to a viewport position(on the 3D camera), then converting that position to the world position (on the 2D camera). What i wanted to say is that you don't need to do those 2 things, you only need to take the 3D position and do WorldToViewport on the 2D Camera public Vector2 Convert3DPositionTo2DPosition(Camera camera3D, Vector3 position3D, Camera camera2D) { return camera2D.WorldToViewportPoint(position3D); } \$\endgroup\$ – Milos Romanic Aug 28 '19 at 8:31

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.