Skip to content

Instantly share code, notes, and snippets.

@romainPechot
Created July 2, 2015 14:14
Show Gist options
  • Save romainPechot/77e3221d4120e7318871 to your computer and use it in GitHub Desktop.
Save romainPechot/77e3221d4120e7318871 to your computer and use it in GitHub Desktop.
Set an object width scale relative to a screen pixel value.
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