babylon.freecamera.input.deviceorientation.ts 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. module BABYLON {
  2. export class FreeCameraDeviceOrientationInput implements ICameraInput<FreeCamera> {
  3. camera: FreeCamera;
  4. private _offsetX: number = null;
  5. private _offsetY: number = null;
  6. private _orientationGamma: number = 0;
  7. private _orientationBeta: number = 0;
  8. private _initialOrientationGamma: number = 0;
  9. private _initialOrientationBeta: number = 0;
  10. private _orientationChanged: (e: DeviceOrientationEvent) => any;
  11. private _resetOrientationGamma: () => any;
  12. @serialize()
  13. public angularSensibility: number = 10000.0;
  14. @serialize()
  15. public moveSensibility: number = 50.0;
  16. constructor() {
  17. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  18. this._orientationChanged = this.orientationChanged.bind(this);
  19. }
  20. attachControl(element : HTMLElement, noPreventDefault?: boolean) {
  21. window.addEventListener("resize", this._resetOrientationGamma, false);
  22. window.addEventListener("deviceorientation", this._orientationChanged);
  23. }
  24. resetOrientationGamma() {
  25. this._initialOrientationGamma = null;
  26. }
  27. orientationChanged(evt) {
  28. if (!this._initialOrientationGamma) {
  29. this._initialOrientationGamma = evt.gamma;
  30. this._initialOrientationBeta = evt.beta;
  31. }
  32. this._orientationGamma = evt.gamma;
  33. this._orientationBeta = evt.beta;
  34. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  35. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  36. }
  37. detachControl(element : HTMLElement) {
  38. window.removeEventListener("resize", this._resetOrientationGamma);
  39. window.removeEventListener("deviceorientation", this._orientationChanged);
  40. this._orientationGamma = 0;
  41. this._orientationBeta = 0;
  42. this._initialOrientationGamma = 0;
  43. this._initialOrientationBeta = 0;
  44. }
  45. public checkInputs() {
  46. if (!this._offsetX) {
  47. return;
  48. }
  49. var camera = this.camera;
  50. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  51. var speed = camera._computeLocalCameraSpeed();
  52. var direction = new Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  53. Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54. camera.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  55. }
  56. getTypeName(): string {
  57. return "FreeCameraDeviceOrientationInput";
  58. }
  59. getSimpleName(){
  60. return "deviceOrientation";
  61. }
  62. }
  63. CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  64. }