Skip to content

Instantly share code, notes, and snippets.

@brihernandez
Last active April 25, 2022 21:51
Show Gist options
  • Save brihernandez/e8b2acb120569855c30a74460db56b9e to your computer and use it in GitHub Desktop.
Save brihernandez/e8b2acb120569855c30a74460db56b9e to your computer and use it in GitHub Desktop.
TrailRenderer that maintains a width in screen space (URP)
public class PixelPerfectTrail : MonoBehaviour
{
[SerializeField] private TrailRenderer trail = null;
[Tooltip("How small the trail width is allowed to get in pixels.")]
public float MinimumPixelSize = 1.5f;
private float startSize = 1f;
private void Awake()
{
startSize = trail.widthMultiplier;
}
private void OnEnable()
{
RenderPipelineManager.beginCameraRendering += ScaleWithDistance;
}
private void OnDisable()
{
RenderPipelineManager.beginCameraRendering -= ScaleWithDistance;
}
private void ScaleWithDistance(ScriptableRenderContext context, Camera cam)
{
float distance = Vector3.Distance(cam.transform.position, transform.position);
float currentPixelSize = DistanceAndDiameterToPixelSize(distance, startSize, cam);
if (currentPixelSize < MinimumPixelSize)
{
float scaledWidth = PixelSizeAndDistanceToDiameter(MinimumPixelSize, distance, cam);
trail.widthMultiplier = scaledWidth;
}
else
{
trail.widthMultiplier = startSize;
}
}
// Get the diameter of an object, given its screen size in pixels and distance. By Elecman:
// https://forum.unity.com/threads/this-script-gives-you-objects-screen-size-in-pixels.48966/#post-2107126
private float PixelSizeAndDistanceToDiameter(float pixelSize, float distance, Camera cam)
{
float diameter = (pixelSize * distance * cam.fieldOfView) / (Mathf.Rad2Deg * Screen.height);
return diameter;
}
// Get the screen size of an object in pixels, given its distance and diameter. By Elecman:
// https://forum.unity.com/threads/this-script-gives-you-objects-screen-size-in-pixels.48966/#post-2107126
private float DistanceAndDiameterToPixelSize(float distance, float diameter, Camera cam)
{
float pixelSize = (diameter * Mathf.Rad2Deg * Screen.height) / (distance * cam.fieldOfView);
return pixelSize;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment