deviceOrientationCamera.ts 3.0 KB

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