Files

72 lines
2.2 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using TMPro;
// 滑鼠回報率 : 用 Raw Input 每一筆回報的真實時間戳算出來 (跟遊戲中記錄的是同一份資料)
// 同時也是 Raw Input 有沒有正常運作的檢查
public class Polling : MonoBehaviour
{
[Header("UI 參照")]
[Tooltip("Text (TMP) ")]
public TextMeshProUGUI pollingDisplay;
[Header("顯示")]
[Tooltip("文字更新間隔 (秒)")]
public float updateInterval = 0.5f;
[Tooltip("超過這麼久沒移動就顯示 0 (秒)")]
public float idleTimeout = 2f;
// 間隔超過這個就算是停下來了,不拿來算回報率 (秒)
private const double MaxGap = 0.02;
private readonly List<double> gaps = new List<double>();
private double lastEventTime;
private float displayTimer;
private float idleTimer;
private int shownHz = -1;
void Update()
{
if (!RawMouseInput.IsRunning)
{
SetText("滑鼠回報率: 無法偵測 (" + RawMouseInput.Status + ")", -2);
return;
}
foreach (RawMouseInput.Event e in RawMouseInput.FrameEvents)
{
if (e.dx == 0 && e.dy == 0) continue; // 只有按鍵變化的回報不算
double gap = e.t - lastEventTime;
if (lastEventTime > 0 && gap > 0 && gap < MaxGap) gaps.Add(gap);
lastEventTime = e.t;
idleTimer = 0f;
}
idleTimer += Time.unscaledDeltaTime;
displayTimer += Time.unscaledDeltaTime;
if (displayTimer < updateInterval) return;
displayTimer = 0f;
// 取間隔的中位數 : 滑鼠慢慢動時偶爾會少送幾筆,中位數比平均穩定
if (gaps.Count >= 10)
{
gaps.Sort();
int hz = Mathf.RoundToInt((float)(1.0 / gaps[gaps.Count / 2]));
SetText($"滑鼠回報率: {hz} Hz", hz);
}
else if (idleTimer > idleTimeout)
{
SetText("滑鼠回報率: 0 Hz", 0);
}
gaps.Clear();
}
void SetText(string text, int code)
{
if (pollingDisplay == null || code == shownHz) return;
shownHz = code;
pollingDisplay.text = text;
}
}