DaydreamController.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /**
  2. * @author Mugen87 / https://github.com/Mugen87
  3. */
  4. THREE.DaydreamController = function () {
  5. THREE.Object3D.call( this );
  6. var scope = this;
  7. var gamepad;
  8. var axes = [ 0, 0 ];
  9. var touchpadIsPressed = false;
  10. var angularVelocity = new THREE.Vector3();
  11. this.matrixAutoUpdate = false;
  12. function findGamepad() {
  13. // iterate across gamepads as the Daydream Controller may not be in position 0
  14. var gamepads = navigator.getGamepads();
  15. for ( var i = 0; i < 4; i ++ ) {
  16. var gamepad = gamepads[ i ];
  17. if ( gamepad && ( gamepad.id === 'Daydream Controller' ) ) {
  18. return gamepad;
  19. }
  20. }
  21. }
  22. this.getGamepad = function () {
  23. return gamepad;
  24. };
  25. this.getTouchPadState = function () {
  26. return touchpadIsPressed;
  27. };
  28. this.update = function () {
  29. gamepad = findGamepad();
  30. if ( gamepad !== undefined && gamepad.pose !== undefined ) {
  31. var pose = gamepad.pose;
  32. if ( pose === null ) return; // no user action yet
  33. // orientation
  34. if ( pose.orientation !== null ) scope.quaternion.fromArray( pose.orientation );
  35. scope.updateMatrix();
  36. scope.visible = true;
  37. // angular velocity
  38. if ( pose.angularVelocity !== null && ! angularVelocity.equals( pose.angularVelocity ) ) {
  39. angularVelocity.fromArray( pose.angularVelocity );
  40. scope.dispatchEvent( { type: 'angularvelocitychanged', angularVelocity: angularVelocity } );
  41. }
  42. // axes (touchpad)
  43. if ( axes[ 0 ] !== gamepad.axes[ 0 ] || axes[ 1 ] !== gamepad.axes[ 1 ] ) {
  44. axes[ 0 ] = gamepad.axes[ 0 ];
  45. axes[ 1 ] = gamepad.axes[ 1 ];
  46. scope.dispatchEvent( { type: 'axischanged', axes: axes } );
  47. }
  48. // button (touchpad)
  49. if ( touchpadIsPressed !== gamepad.buttons[ 0 ].pressed ) {
  50. touchpadIsPressed = gamepad.buttons[ 0 ].pressed;
  51. scope.dispatchEvent( { type: touchpadIsPressed ? 'touchpaddown' : 'touchpadup' } );
  52. }
  53. // app button not available, reserved for use by the browser
  54. } else {
  55. scope.visible = false;
  56. }
  57. };
  58. };
  59. THREE.DaydreamController.prototype = Object.create( THREE.Object3D.prototype );
  60. THREE.DaydreamController.prototype.constructor = THREE.DaydreamController;