DaydreamController.js 2.4 KB

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