17 private struct HapticEffect
19 public int hMaterialId;
20 public double duration;
22 public double intensity;
23 public float vibrationOffset;
25 public HapticEffect(
int hMaterialId,
double duration,
int loops,
double intensity,
float vibrationOffset)
27 this.hMaterialId = hMaterialId;
28 this.duration = duration;
30 this.intensity = intensity;
31 this.vibrationOffset = vibrationOffset;
35 private Queue<HapticEffect> hapticEffectsQueue =
new Queue<HapticEffect>();
36 private bool isPlaying =
false;
37 private Coroutine playingCoroutine =
null;
41 if (currentInstance !=
null && currentInstance !=
this)
47 currentInstance =
this;
48 DontDestroyOnLoad(gameObject);
52 public static void EnqueueEffect(
int hMaterialId,
double duration,
int loops,
double intensity,
float vibrationOffset = 0f)
54 if (currentInstance ==
null)
56 GameObject mobileControllerObject =
new GameObject(
"MobileController");
57 currentInstance = mobileControllerObject.AddComponent<
MobileControl>();
58 DontDestroyOnLoad(mobileControllerObject);
61 currentInstance.EnqueueEffectInternal(
new HapticEffect(hMaterialId, duration, loops, intensity, vibrationOffset));
64 private void EnqueueEffectInternal(HapticEffect effect)
73 hapticEffectsQueue.Clear();
74 hapticEffectsQueue.Enqueue(effect);
78 private void PlayNextEffect()
80 if (hapticEffectsQueue.Count > 0 && !isPlaying)
82 var effect = hapticEffectsQueue.Dequeue();
83 playingCoroutine = StartCoroutine(PlayHapticEffect(effect));
87 private IEnumerator PlayHapticEffect(HapticEffect effect)
89 if (effect.vibrationOffset > 0)
91 yield
return new WaitForSeconds(effect.vibrationOffset);
96 HAR.SetEventIntensity(effect.hMaterialId, effect.intensity);
98 for (
int i = 1; i <= effect.loops; i++)
100 HAR.PlayEvent(effect.hMaterialId, (
double)-Time.realtimeSinceStartup, 0, 0);
101 Debug.Log($
"Playing haptic effect: Material ID {effect.hMaterialId}, Loop {i}/{effect.loops}");
102 yield
return new WaitForSeconds((
float)effect.duration);
109 private void StopCurrentEffect()
111 if (playingCoroutine !=
null)
113 StopCoroutine(playingCoroutine);
114 playingCoroutine =
null;
122 if (currentInstance !=
null)
124 currentInstance.StopCurrentEffect();
125 currentInstance.hapticEffectsQueue.Clear();
126 Debug.Log(
"All haptic effects stopped.");