Search Unity

cam.WorldToScreenPoint(pos) works strangley when using cinemachine

Discussion in 'Cinemachine' started by Rajmahal, Feb 25, 2021.

  1. Rajmahal

    Rajmahal

    Joined:
    Apr 20, 2011
    Posts:
    2,101
    Hi,

    I have an existing script that positions a UI text (using NGUI) object on a particular position to display damage on a unit during the game. The position is derived from the following:

    Vector3 screenPos = cam.WorldToScreenPoint(pos);

    However, when I'm not using cinemachine, this seems to work fine. However, once I put a cinemachinebrain on the maincam and switch to virtualcams, the same code no longer seems to position the text on the right position. The "cam" variable is just a reference to the main camera that has the cinemachinebrain on it.

    Is there something that needs to be done differently when using cinemahine? My understanding was that a virtual camera is just a transform that the main Camera (with the CinemachienBrain) positions itself on during runtime. Therefore, I would imagine this would still work.
     
  2. Gregoryl

    Gregoryl

    Unity Technologies

    Joined:
    Dec 22, 2016
    Posts:
    7,724
    Yes, this should work as you describe. However, with Cinemachine, the camera position is updated very late in the frame, and if this happens after your WorldToScreenPoint call, then you will be using a stale camera position. You have to make the call after the main camera's transform is updated.

    The easiest way to do this is to use CinemachineCore.CameraUpdatedEvent, and put your call in a handler registered with that event.
     
    Rajmahal likes this.
  3. Rajmahal

    Rajmahal

    Joined:
    Apr 20, 2011
    Posts:
    2,101
    Thanks .. appreciate the reply. That's certainly helpful.
     
    Gregoryl likes this.