Haptics.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Runtime.InteropServices;
  5. public delegate void FPtr(int value);
  6. public class Haptics : MonoBehaviour
  7. {
  8. private int interfaceId;
  9. class EAIWrapper
  10. {
  11. [DllImport("TactorInterface.dll", CallingConvention = CallingConvention.Cdecl)]
  12. public static extern int InitializeTI();
  13. [DllImport("TactorInterface.dll", CallingConvention = CallingConvention.Cdecl)]
  14. public static extern int Discover(int type);
  15. [DllImport("TactorInterface.dll", CallingConvention = CallingConvention.Cdecl)]
  16. public static extern int Connect([MarshalAs(UnmanagedType.LPStr)] string name, int type, FPtr _callback);
  17. [DllImport("TactorInterface.dll", CallingConvention = CallingConvention.Cdecl)]
  18. public static extern int Pulse(int deviceId, int _tacNum, int _msDuration, int _delay);
  19. [DllImport("TactorInterface.dll", CallingConvention = CallingConvention.Cdecl)]
  20. public static extern int ChangeFreq(int deviceId, int _tacNum, int freqVal, int _delay);
  21. [DllImport("TactorInterface.dll", CallingConvention = CallingConvention.Cdecl)]
  22. public static extern int ChangeGain(int deviceID, int _tacNum, int gainval, int _delay);
  23. [DllImport("TactorInterface.dll", CallingConvention = CallingConvention.Cdecl)]
  24. public static extern int Close(int interfaceId);
  25. [DllImport("TactorInterface.dll", CallingConvention = CallingConvention.Cdecl)]
  26. public static extern int ShutdownTI();
  27. }
  28. void Start()
  29. {
  30. EAIWrapper.InitializeTI();
  31. EAIWrapper.Discover(1);
  32. interfaceId = EAIWrapper.Connect("COM5", 1, null);
  33. }
  34. /// <summary>
  35. /// Vibrate a haptic motor
  36. /// </summary>
  37. /// <param name="motor">Motor: 1-16</param>
  38. /// <param name="intensity">Intensity range: 0.0-1.0</param>
  39. /// <param name="vibrationTime">Vibration time in miliseconds</param>
  40. public void Vibrate(int motor, double intensity, int vibrationTime)
  41. {
  42. EAIWrapper.ChangeGain(interfaceId, motor, (int)(intensity * 255), 0);
  43. EAIWrapper.Pulse(interfaceId, motor, vibrationTime, 0);
  44. EAIWrapper.ChangeFreq(interfaceId, motor, 2000, 0);
  45. }
  46. private void OnDestroy()
  47. {
  48. EAIWrapper.Close(interfaceId);
  49. EAIWrapper.ShutdownTI();
  50. }
  51. private void Update()
  52. {
  53. if (Input.GetKey(KeyCode.A))
  54. {
  55. Vibrate(15, 1, 100);
  56. }
  57. if (Input.GetKey(KeyCode.S))
  58. {
  59. Vibrate(16, 1, 100);
  60. }
  61. if (Input.GetKey(KeyCode.D))
  62. {
  63. for (int i = 1; i <= 16; i++)
  64. {
  65. Vibrate(i, 1, 100);
  66. }
  67. }
  68. }
  69. }