Search Unity

Camera.WorldToViewportPoint math

Discussion in 'General Graphics' started by FrankvHoof, Mar 14, 2019.

  1. FrankvHoof

    FrankvHoof

    Joined:
    Nov 3, 2014
    Posts:
    258
    Not sure if this (graphics) is the proper forum, but it seems closest to my aims.

    I'm trying to jobify a piece of my code that checks whether an object is in the viewport of a camera.
    To do this, I need to get the matrix used in WorldToViewportPoint(Vector3 position) (as I can't use the Camera-class itself in a job).
    The code is 'hidden', and I can't seem to get any of the matrices that I can pull from a camera (e.g. ProjectionMatrix, WorldToCameraMatrix) to get me the same result as the method.
    Can somebody tell me how I would implement WorldToViewportPoint using matrices I can pull from the Camera?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,352
    roughly

    Code (csharp):
    1. Vector4 worldPos = new Vector4(position.x, position.y, position.z, 1.0);
    2. Vector4 viewPos = camera.worldToCameraMatrix * worldPos;
    3. Vector4 projPos = camera.projectionMatrix * viewPos;
    4. Vector3 ndcPos = new Vector3(projPos.x / projPos.w, projPos.y / projPos.w, projPos.z / projPos.w);
    5. Vector3 viewportPos = new Vector3(ndcPos.x * 0.5 + 0.5, ndcPos.y * 0.5 + 0.5, -viewPos.z);