babylon.vrDeviceOrientationCamera.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. module BABYLON {
  2. export class VRDeviceOrientationFreeCamera extends 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, compensateDistorsion = true) {
  9. super(name, position, scene);
  10. var metrics = VRCameraMetrics.GetDefault();
  11. metrics.compensateDistorsion = compensateDistorsion;
  12. this.setCameraRigMode(Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  13. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14. }
  15. public _onOrientationEvent(evt: DeviceOrientationEvent): void {
  16. this._alpha = +evt.alpha|0;
  17. this._beta = +evt.beta|0;
  18. this._gamma = +evt.gamma|0;
  19. if (this._gamma < 0) {
  20. this._gamma = 90 + this._gamma;
  21. }
  22. else {
  23. // Incline it in the correct angle.
  24. this._gamma = 270 - this._gamma;
  25. }
  26. this.rotation.x = this._gamma / 180.0 * Math.PI;
  27. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28. this.rotation.z = this._beta / 180.0 * Math.PI;
  29. }
  30. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  31. super.attachControl(element, noPreventDefault);
  32. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  33. }
  34. public detachControl(element: HTMLElement): void {
  35. super.detachControl(element);
  36. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  37. }
  38. }
  39. }