VRControls.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 && !navigator.getVRDevices ) {
  9. if ( done ) {
  10. done("Your browser is not VR Ready");
  11. }
  12. return;
  13. }
  14. if ( navigator.getVRDevices ) {
  15. navigator.getVRDevices().then( gotVRDevices );
  16. } else {
  17. navigator.mozGetVRDevices( gotVRDevices );
  18. }
  19. function gotVRDevices( devices ) {
  20. var vrInput;
  21. var error;
  22. for ( var i = 0; i < devices.length; ++i ) {
  23. if ( devices[i] instanceof PositionSensorVRDevice ) {
  24. vrInput = devices[i]
  25. self._vrInput = vrInput;
  26. break; // We keep the first we encounter
  27. }
  28. }
  29. if ( done ) {
  30. if ( !vrInput ) {
  31. error = 'HMD not available';
  32. }
  33. done( error );
  34. }
  35. }
  36. };
  37. this._init();
  38. this.update = function() {
  39. var camera = this._camera;
  40. var quat;
  41. var vrState = this.getVRState();
  42. if ( !vrState ) {
  43. return;
  44. }
  45. // Applies head rotation from sensors data.
  46. if ( camera ) {
  47. camera.quaternion.fromArray( vrState.hmd.rotation );
  48. }
  49. };
  50. this.getVRState = function() {
  51. var vrInput = this._vrInput;
  52. var orientation;
  53. var vrState;
  54. if ( !vrInput ) {
  55. return null;
  56. }
  57. orientation = vrInput.getState().orientation;
  58. vrState = {
  59. hmd : {
  60. rotation : [
  61. orientation.x,
  62. orientation.y,
  63. orientation.z,
  64. orientation.w
  65. ]
  66. }
  67. };
  68. return vrState;
  69. };
  70. };