VR手柄的绘制

  1. /*
  2. * Author : shenjun
  3. */
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using UnityEngine;
  7. using Valve.VR;
  8. /// <summary>
  9. /// 实现手柄的绘制
  10. /// </summary>
  11. [RequireComponent(typeof(SteamVR_RenderModel))]
  12. public class HandTest : MonoBehaviour {
  13. public enum HandType
  14. {
  15. LeftHand,
  16. RightHand,
  17. }
  18. public HandType handType = HandType.RightHand;
  19. uint index; // 设备索引值
  20. SteamVR_Controller.Device controller; // 控制手柄
  21. SteamVR_Events.Action newPosAction; // 手柄位置更新
  22. void Awake()
  23. {
  24. newPosAction = SteamVR_Events.NewPosesAction(OnNewPos); // 创建位置更新对象
  25. }
  26. void OnEnable()
  27. {
  28. newPosAction.enabled = true; // 绑定位置更新回调方法
  29. }
  30. void OnDisable()
  31. {
  32. newPosAction.enabled = false; // 解除位置更新回调方法的绑定
  33. }
  34. IEnumerator Start()
  35. {
  36. while (controller == null)
  37. {
  38. yield return new WaitForSeconds(1.0f);
  39. var system = OpenVR.System;
  40. if (system != null)
  41. {
  42. if (handType == HandType.LeftHand)
  43. {
  44. index = system.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.LeftHand);
  45. }
  46. else
  47. {
  48. index = system.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.RightHand);
  49. }
  50. if (index == OpenVR.k_unTrackedDeviceIndexInvalid)
  51. {
  52. continue;
  53. }
  54. SetDeviceIndex((int)index);
  55. }
  56. }
  57. }
  58. /// <summary>
  59. /// 设置设备的索引
  60. /// </summary>
  61. /// <param name="index"></param>
  62. private void SetDeviceIndex(int index)
  63. {
  64. if (controller == null)
  65. {
  66. controller = SteamVR_Controller.Input(index);
  67. SteamVR_RenderModel r = GetComponent<SteamVR_RenderModel>();
  68. if(r)
  69. {
  70. r.SetDeviceIndex(index);
  71. }
  72. }
  73. }
  74. /// <summary>
  75. /// 设备位置更新
  76. /// </summary>
  77. /// <param name="poses"></param>
  78. private void OnNewPos(TrackedDevicePose_t[] poses)
  79. {
  80. if (index == OpenVR.k_unTrackedDeviceIndexInvalid) return;
  81. if (index >= poses.Length) return;
  82. if(poses[index].bDeviceIsConnected && poses[index].bPoseIsValid)
  83. {
  84. var pos = new SteamVR_Utils.RigidTransform(poses[index].mDeviceToAbsoluteTracking);
  85. transform.localPosition = pos.pos;
  86. transform.localRotation = pos.rot;
  87. }
  88. }
  89. }