babylon.vrDeviceOrientationCamera.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. module BABYLON {
  2. export class VRDeviceOrientationFreeCamera extends BABYLON.FreeCamera {
  3. public _alpha = 0;
  4. public _beta = 0;
  5. public _gamma = 0;
  6. private _offsetOrientation: { yaw: number; pitch: number; roll: number };
  7. private _deviceOrientationHandler;
  8. constructor(name: string, position: Vector3, scene: Scene) {
  9. super(name, position, scene);
  10. this.setSubCameraMode(Camera.SUB_CAMERA_MODE_VR);
  11. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12. }
  13. public _onOrientationEvent(evt: DeviceOrientationEvent): void {
  14. this._alpha = +evt.alpha|0;
  15. this._beta = +evt.beta|0;
  16. this._gamma = +evt.gamma|0;
  17. if (this._gamma < 0) {
  18. this._gamma = 90 + this._gamma;
  19. }
  20. else {
  21. // Incline it in the correct angle.
  22. this._gamma = 270 - this._gamma;
  23. }
  24. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26. this.rotation.z = this._beta / 180.0 * Math.PI;
  27. }
  28. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  29. super.attachControl(element, noPreventDefault);
  30. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31. }
  32. public detachControl(element: HTMLElement): void {
  33. super.detachControl(element);
  34. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  35. }
  36. }
  37. }