babylon.deviceOrientationCamera.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. module BABYLON {
  2. // We're mainly based on the logic defined into the FreeCamera code
  3. export class DeviceOrientationCamera extends 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 _attachedCanvas: HTMLCanvasElement;
  11. private _orientationChanged: (e: DeviceOrientationEvent) => any;
  12. public angularSensibility: number = 10000.0;
  13. public moveSensibility: number = 50.0;
  14. constructor(name: string, position: Vector3, scene: Scene) {
  15. super(name, position, scene);
  16. window.addEventListener("resize", () => {
  17. this._initialOrientationGamma = null;
  18. }, false);
  19. }
  20. public attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void {
  21. if (this._attachedCanvas) {
  22. return;
  23. }
  24. this._attachedCanvas = canvas;
  25. if (!this._orientationChanged) {
  26. this._orientationChanged = (evt) => {
  27. if (!this._initialOrientationGamma) {
  28. this._initialOrientationGamma = evt.gamma;
  29. this._initialOrientationBeta = evt.beta;
  30. }
  31. this._orientationGamma = evt.gamma;
  32. this._orientationBeta = evt.beta;
  33. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  34. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  35. };
  36. }
  37. window.addEventListener("deviceorientation", this._orientationChanged);
  38. }
  39. public detachControl(canvas: HTMLCanvasElement): void {
  40. if (this._attachedCanvas != canvas) {
  41. return;
  42. }
  43. window.removeEventListener("deviceorientation", this._orientationChanged);
  44. this._attachedCanvas = null;
  45. this._orientationGamma = 0;
  46. this._orientationBeta = 0;
  47. this._initialOrientationGamma = 0;
  48. this._initialOrientationBeta = 0;
  49. }
  50. public _checkInputs(): void {
  51. if (!this._offsetX) {
  52. return;
  53. }
  54. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  55. var speed = this._computeLocalCameraSpeed();
  56. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  57. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  58. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  59. super._checkInputs();
  60. }
  61. }
  62. }