Thursday, June 12, 2014

Unity3d C# Code to Convert Screen Size to World Co-ordinates

C# code to convert screen size to world co-ordinates,

Vector2 GetScreenSizeInWorldCoords()
{
   Camera cam = Camera.main;
   Vector3 p1 = cam.ViewportToWorldPoint(new Vector3(0,0,cam.nearClipPlane));
   Vector3 p2 = cam.ViewportToWorldPoint(new Vector3(1,0,cam.nearClipPlane));
   Vector3 p3 = cam.ViewportToWorldPoint(new Vector3(1,1,cam.nearClipPlane));

   float width = (p2 - p1).magnitude;
   float height = (p3 - p2).magnitude;

   Vector2 dimensions = new Vector2(width,height);

   return dimensions;
}

No comments:

Post a Comment

Popular Posts