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\$

1 Answer 1

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

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Can you explain why going via screen coordinates would have a different result than going via viewport coordinates? \$\endgroup\$
    – DMGregory
    Aug 27, 2019 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\$
    – Kaynnc
    Aug 28, 2019 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\$ Aug 28, 2019 at 8:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .