-
Notifications
You must be signed in to change notification settings - Fork 1
/
URP_Autofocus.cs
80 lines (70 loc) · 2.18 KB
/
URP_Autofocus.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
[RequireComponent(typeof(Camera))]
public class DofFocus : MonoBehaviour
{
private Camera cameraMain;
public VolumeProfile postFxProfile;
private DepthOfField dof;
private MinFloatParameter dofDistanceParametar;
private Ray ray;
private RaycastHit hit;
private Vector3 viewportCenter;
public LayerMask mask;
// private bool isHit = false;
public float defaultDistance = 5f;
public float minDistance = 0.5f;
private float hitDistance;
public float focusSpeed = 1f;
public int updateFrequency = 2;
private Transform thisTransform;
private void Awake()
{
thisTransform = transform;
}
private void Start()
{
postFxProfile.TryGet<DepthOfField>(out dof);
dofDistanceParametar = dof.focusDistance;
viewportCenter = new Vector3(0.5f, 0.5f, 0);
cameraMain = GetComponent<Camera>();
}
private void Update()
{
if (Time.frameCount % updateFrequency == 0)
{
ray = cameraMain.ViewportPointToRay(viewportCenter);
if (Physics.Raycast(ray, out hit, defaultDistance - 0.1f, mask))
{
// isHit = true;
hitDistance = hit.distance;
if (hitDistance < minDistance)
{
hitDistance = minDistance;
}
dofDistanceParametar.value = Mathf.Lerp(dofDistanceParametar.value, hitDistance, focusSpeed);
}
else
{
// isHit = false;
if (dofDistanceParametar.value < defaultDistance)
{
dofDistanceParametar.value = Mathf.Lerp(dofDistanceParametar.value, defaultDistance, focusSpeed);
}
}
}
}
// private void OnDrawGizmos()
// {
// if (isHit)
// {
// Gizmos.DrawSphere(hit.point, 0.1f);
// Debug.DrawRay(thisTransform.position, thisTransform.forward * hitDistance);
// }
// else
// {
// Debug.DrawRay(thisTransform.position, thisTransform.forward * 1000f);
// }
// }
}