DynamicDoF.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Linq;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5. using UnityEngine.Rendering;
  6. using UnityEngine.Rendering.Universal;
  7. namespace SicknessReduction.Visual.DoF
  8. {
  9. public class DynamicDoF : MonoBehaviour
  10. {
  11. public Camera playerCamera;
  12. public VolumeProfile postProcessProfile;
  13. private Transform cameraTransform;
  14. private DepthOfField doF;
  15. private bool doFAvailable;
  16. private void Start()
  17. {
  18. cameraTransform = playerCamera.transform;
  19. doF = (DepthOfField) postProcessProfile.components.FirstOrDefault(c => c is DepthOfField);
  20. doFAvailable = doF != null;
  21. if (doFAvailable)
  22. {
  23. // ReSharper disable once PossibleNullReferenceException
  24. doF.mode.value = DepthOfFieldMode.Bokeh;
  25. }
  26. else
  27. {
  28. Debug.LogWarning("No DepthOfField found in PostProcessing Profile!");
  29. }
  30. }
  31. private void Update()
  32. {
  33. if(!doFAvailable) return;
  34. var focalDistance = CastRay();
  35. if (focalDistance < 0)
  36. {
  37. doF.active = false;
  38. return;
  39. }
  40. doF.active = true;
  41. doF.focusDistance.value = focalDistance;
  42. doF.focalLength.value = focalDistance * 10;
  43. }
  44. private float CastRay()
  45. {
  46. var position = cameraTransform.position;
  47. var forward = cameraTransform.forward;
  48. var start = position + forward * playerCamera.nearClipPlane;
  49. var end = position + forward * playerCamera.farClipPlane;
  50. if (Physics.Linecast(start, end, out var hit, Physics.DefaultRaycastLayers))
  51. {
  52. Debug.DrawLine(start, end, Color.green);
  53. Debug.Log("DoF - Hit, Distance = "+hit.distance);
  54. return hit.distance;
  55. }
  56. Debug.DrawRay(position, position + forward * playerCamera.farClipPlane, Color.red);
  57. Debug.Log("DoF - No hit");
  58. return -1f;
  59. }
  60. }
  61. }