Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.1 KiB

  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.controller != null ) && ( hand.GetStandardInteractionButton() ) )
  59. {
  60. ushort duration = (ushort)Random.Range( minimumPulseDuration, maximumPulseDuration + 1 );
  61. hand.controller.TriggerHapticPulse( duration );
  62. onPulse.Invoke();
  63. }
  64. }
  65. }
  66. }