Piece of code to convert from world space size to pixel size. Handy if you need to fit something to a pixel sized displayed area in a UI.

All you need is to supply the size of the object in world space and the distance from the camera to the object.

private Vector2 GetSizeAtDepth(Vector2 a_size, float a_depth, Camera a_camera)
{
    float fov2 = a_camera.fieldOfView * Mathf.PI / 360.0f;
    float height = Mathf.Tan(fov2) * a_depth * 2.0f;

    float pixelHeight = (a_size.y / height) * Screen.height;
    float pixelWidth = (a_size.x / (height * a_camera.aspect)) * Screen.width;

    return new Vector2(pixelWidth, pixelHeight);
}

 

Call it with something like the code below and it’ll return pixel sizes using the current screen res.

float depth = 8.0f;
Vector2 res = GetSizeAtDepth(new Vector2(10.0f, 10.0f), depth, m_renderCamera);

Debug.Log("pixelWidth: " + res.x);
Debug.Log("pixelHeight: " + res.y);

 

So, this is passing in a 10 x 10 x/y as the world space size (size of a standard Unity plane).

The ‘depth’ is the distance from the camera to the object. As the object is a plane that’s facing the camera, we don’t need to find a specific depth within the object. i.e. if it was a sphere then we’d have to decide if we wanted depth to the front, middle or back.

m_renderCamera is just a standard Unity camera.

Obviously, this can easily be adapted to work without Unity but I’m using it to get something up and running quickly.

Hope it helps!

 

 


Discover more from

Subscribe to get the latest posts sent to your email.

Leave a comment

Trending