VRControls.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * @author dmarcos / https://github.com/dmarcos
  3. */
  4. THREE.VRControls = function ( camera, done ) {
  5. this._camera = camera;
  6. this._init = function () {
  7. var self = this;
  8. if ( !navigator.mozGetVRDevices ) {
  9. if ( done ) {
  10. done("Your browser is not VR Ready");
  11. }
  12. return;
  13. }
  14. navigator.mozGetVRDevices( gotVRDevices );
  15. function gotVRDevices( devices ) {
  16. var vrInput;
  17. var error;
  18. for ( var i = 0; i < devices.length; ++i ) {
  19. if ( devices[i] instanceof PositionSensorVRDevice ) {
  20. vrInput = devices[i]
  21. self._vrInput = vrInput;
  22. break; // We keep the first we encounter
  23. }
  24. }
  25. if ( done ) {
  26. if ( !vrInput ) {
  27. error = 'HMD not available';
  28. }
  29. done( error );
  30. }
  31. }
  32. };
  33. this._init();
  34. this.update = function() {
  35. var camera = this._camera;
  36. var quat;
  37. var vrState = this.getVRState();
  38. if ( !vrState ) {
  39. return;
  40. }
  41. // Applies head rotation from sensors data.
  42. if ( camera ) {
  43. quat = new THREE.Quaternion(
  44. vrState.hmd.rotation[0],
  45. vrState.hmd.rotation[1],
  46. vrState.hmd.rotation[2],
  47. vrState.hmd.rotation[3]
  48. );
  49. camera.setRotationFromQuaternion( quat );
  50. }
  51. };
  52. this.getVRState = function() {
  53. var vrInput = this._vrInput;
  54. var orientation;
  55. var vrState;
  56. if ( !vrInput ) {
  57. return null;
  58. }
  59. orientation = vrInput.getState().orientation;
  60. vrState = {
  61. hmd : {
  62. rotation : [
  63. orientation.x,
  64. orientation.y,
  65. orientation.z,
  66. orientation.w
  67. ]
  68. }
  69. };
  70. return vrState;
  71. };
  72. };