HapticRack.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
  2. //
  3. // Purpose: Triggers haptic pulses based on a linear mapping
  4. //
  5. //=============================================================================
  6. using UnityEngine;
  7. using UnityEngine.Events;
  8. using System.Collections;
  9. namespace Valve.VR.InteractionSystem
  10. {
  11. //-------------------------------------------------------------------------
  12. [RequireComponent( typeof( Interactable ) )]
  13. public class HapticRack : MonoBehaviour
  14. {
  15. [Tooltip( "The linear mapping driving the haptic rack" )]
  16. public LinearMapping linearMapping;
  17. [Tooltip( "The number of haptic pulses evenly distributed along the mapping" )]
  18. public int teethCount = 128;
  19. [Tooltip( "Minimum duration of the haptic pulse" )]
  20. public int minimumPulseDuration = 500;
  21. [Tooltip( "Maximum duration of the haptic pulse" )]
  22. public int maximumPulseDuration = 900;
  23. [Tooltip( "This event is triggered every time a haptic pulse is made" )]
  24. public UnityEvent onPulse;
  25. private Hand hand;
  26. private int previousToothIndex = -1;
  27. //-------------------------------------------------
  28. void Awake()
  29. {
  30. if ( linearMapping == null )
  31. {
  32. linearMapping = GetComponent<LinearMapping>();
  33. }
  34. }
  35. //-------------------------------------------------
  36. private void OnHandHoverBegin( Hand hand )
  37. {
  38. this.hand = hand;
  39. }
  40. //-------------------------------------------------
  41. private void OnHandHoverEnd( Hand hand )
  42. {
  43. this.hand = null;
  44. }
  45. //-------------------------------------------------
  46. void Update()
  47. {
  48. int currentToothIndex = Mathf.RoundToInt( linearMapping.value * teethCount - 0.5f );
  49. if ( currentToothIndex != previousToothIndex )
  50. {
  51. Pulse();
  52. previousToothIndex = currentToothIndex;
  53. }
  54. }
  55. //-------------------------------------------------
  56. private void Pulse()
  57. {
  58. if ( hand && (hand.isActive) && ( hand.GetBestGrabbingType() != GrabTypes.None ) )
  59. {
  60. ushort duration = (ushort)Random.Range( minimumPulseDuration, maximumPulseDuration + 1 );
  61. hand.TriggerHapticPulse( duration );
  62. onPulse.Invoke();
  63. }
  64. }
  65. }
  66. }