babylon.deviceOrientationCamera.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. module BABYLON {
  2. // We're mainly based on the logic defined into the FreeCamera code
  3. /**
  4. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  5. * being tilted forward or back and left or right.
  6. */
  7. export class DeviceOrientationCamera extends FreeCamera {
  8. private _initialQuaternion: Quaternion;
  9. private _quaternionCache: Quaternion;
  10. /**
  11. * Creates a new device orientation camera. @see DeviceOrientationCamera
  12. * @param name The name of the camera
  13. * @param position The start position camera
  14. * @param scene The scene the camera belongs to
  15. */
  16. constructor(name: string, position: Vector3, scene: Scene) {
  17. super(name, position, scene);
  18. this._quaternionCache = new Quaternion();
  19. this.inputs.addDeviceOrientation();
  20. }
  21. /**
  22. * Gets the current instance class name ("DeviceOrientationCamera").
  23. * This helps avoiding instanceof at run time.
  24. * @returns the class name
  25. */
  26. public getClassName(): string {
  27. return "DeviceOrientationCamera";
  28. }
  29. /**
  30. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  31. */
  32. public _checkInputs(): void {
  33. super._checkInputs();
  34. this._quaternionCache.copyFrom(this.rotationQuaternion);
  35. if (this._initialQuaternion) {
  36. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  37. }
  38. }
  39. /**
  40. * Reset the camera to its default orientation on the specified axis only.
  41. * @param axis The axis to reset
  42. */
  43. public resetToCurrentRotation(axis: Axis = Axis.Y): void {
  44. //can only work if this camera has a rotation quaternion already.
  45. if (!this.rotationQuaternion) return;
  46. if (!this._initialQuaternion) {
  47. this._initialQuaternion = new Quaternion();
  48. }
  49. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  50. ['x', 'y', 'z'].forEach((axisName) => {
  51. if (!(<any>axis)[axisName]) {
  52. (<any>this._initialQuaternion)[axisName] = 0;
  53. } else {
  54. (<any>this._initialQuaternion)[axisName] *= -1;
  55. }
  56. });
  57. this._initialQuaternion.normalize();
  58. //force rotation update
  59. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  60. }
  61. }
  62. }