Created
July 2, 2015 14:14
-
-
Save romainPechot/77e3221d4120e7318871 to your computer and use it in GitHub Desktop.
Set an object width scale relative to a screen pixel value.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public static class CameraHelper | |
{ | |
public static float GetPixelWidthToWorldScale(Camera camera, Vector3 worldTargetPosition, float pixelWidth) | |
{ | |
return GetPixelWidthToWorldScale(camera, worldTargetPosition, pixelWidth, 1f); | |
}// GetPixelWidthToWorldScale() | |
public static float GetPixelWidthToWorldScale(Camera camera, Vector3 worldTargetPosition, float pixelWidth, float targetMeterWidth) | |
{ | |
if(camera.orthographic) | |
{ | |
Debug.LogWarning("GetWorldScale() doesn't work on orthographic camera at the moment !"); | |
return 1f; | |
} | |
float cameraAspectRatio = (float)camera.pixelWidth; | |
cameraAspectRatio /= (float)camera.pixelHeight; | |
float relativePositionDepth = camera.transform.InverseTransformPoint(worldTargetPosition).z; | |
float ratioPixelWidth = pixelWidth; | |
ratioPixelWidth /= (float)camera.pixelWidth; | |
float size = Mathf.Tan(camera.fieldOfView * Mathf.Deg2Rad * 0.5f) * relativePositionDepth * 2f; | |
return size * cameraAspectRatio * ratioPixelWidth / targetMeterWidth; | |
}// GetPixelWidthToWorldScale() | |
}// CameraHelper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment