Files
2026-02-21 16:45:37 +08:00

95 lines
1.9 KiB
C#

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace VRKeyboard.Utils
{
public class GazeRaycaster : MonoBehaviour
{
public float delayInSeconds = 0.5f;
public float loadingTime;
public Image circle;
private string lastTargetName = string.Empty;
private Coroutine gazeControl;
private void FixedUpdate()
{
Vector3 direction = base.transform.TransformDirection(Vector3.forward);
RaycastHit hitInfo;
if (Physics.Raycast(base.transform.position, direction, out hitInfo))
{
if (hitInfo.transform.tag == "VRGazeInteractable")
{
if (!(lastTargetName == hitInfo.transform.name))
{
if (lastTargetName == string.Empty)
{
lastTargetName = hitInfo.transform.name;
}
if (hitInfo.transform.name != lastTargetName)
{
circle.fillAmount = 0f;
lastTargetName = hitInfo.transform.name;
}
if (gazeControl != null)
{
StopCoroutine(gazeControl);
}
gazeControl = StartCoroutine(FillCircle(hitInfo.transform));
}
}
else
{
if (gazeControl != null)
{
StopCoroutine(gazeControl);
}
ResetGazer();
}
}
else
{
if (gazeControl != null)
{
StopCoroutine(gazeControl);
}
ResetGazer();
}
}
private IEnumerator FillCircle(Transform target)
{
float timer = 0f;
circle.fillAmount = 0f;
yield return new WaitForSeconds(delayInSeconds);
while (timer < loadingTime)
{
timer += Time.deltaTime;
circle.fillAmount = timer / loadingTime;
yield return null;
}
circle.fillAmount = 1f;
if ((bool)target.GetComponent<Button>())
{
target.GetComponent<Button>().onClick.Invoke();
}
ResetGazer();
}
private void ResetGazer()
{
if (circle == null)
{
Debug.LogError("Please assign target loading image, (ie. circle image)");
return;
}
circle.fillAmount = 0f;
lastTargetName = string.Empty;
}
}
}