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