flyCamera.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. import { serialize, serializeAsVector3 } from "../Misc/decorators";
  2. import { Nullable } from "../types";
  3. import { Scene } from "../scene";
  4. import { Vector3, Quaternion } from "../Maths/math";
  5. import { Engine } from "../Engines/engine";
  6. import { AbstractMesh } from "../Meshes/abstractMesh";
  7. import { Collider } from "../Collisions/collider";
  8. import { TargetCamera } from "./targetCamera";
  9. import { FlyCameraInputsManager } from "./flyCameraInputsManager";
  10. import { FlyCameraMouseInput } from "../Cameras/Inputs/flyCameraMouseInput";
  11. import { FlyCameraKeyboardInput } from "../Cameras/Inputs/flyCameraKeyboardInput";
  12. /**
  13. * This is a flying camera, designed for 3D movement and rotation in all directions,
  14. * such as in a 3D Space Shooter or a Flight Simulator.
  15. */
  16. export class FlyCamera extends TargetCamera {
  17. /**
  18. * Define the collision ellipsoid of the camera.
  19. * This is helpful for simulating a camera body, like a player's body.
  20. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  21. */
  22. @serializeAsVector3()
  23. public ellipsoid = new Vector3(1, 1, 1);
  24. /**
  25. * Define an offset for the position of the ellipsoid around the camera.
  26. * This can be helpful if the camera is attached away from the player's body center,
  27. * such as at its head.
  28. */
  29. @serializeAsVector3()
  30. public ellipsoidOffset = new Vector3(0, 0, 0);
  31. /**
  32. * Enable or disable collisions of the camera with the rest of the scene objects.
  33. */
  34. @serialize()
  35. public checkCollisions = false;
  36. /**
  37. * Enable or disable gravity on the camera.
  38. */
  39. @serialize()
  40. public applyGravity = false;
  41. /**
  42. * Define the current direction the camera is moving to.
  43. */
  44. public cameraDirection = Vector3.Zero();
  45. /**
  46. * Define the current local rotation of the camera as a quaternion to prevent Gimbal lock.
  47. * This overrides and empties cameraRotation.
  48. */
  49. public rotationQuaternion: Quaternion;
  50. /**
  51. * Track Roll to maintain the wanted Rolling when looking around.
  52. */
  53. public _trackRoll: number = 0;
  54. /**
  55. * Slowly correct the Roll to its original value after a Pitch+Yaw rotation.
  56. */
  57. public rollCorrect: number = 100;
  58. /**
  59. * Mimic a banked turn, Rolling the camera when Yawing.
  60. * It's recommended to use rollCorrect = 10 for faster banking correction.
  61. */
  62. public bankedTurn: boolean = false;
  63. /**
  64. * Limit in radians for how much Roll banking will add. (Default: 90°)
  65. */
  66. public bankedTurnLimit: number = Math.PI / 2;
  67. /**
  68. * Value of 0 disables the banked Roll.
  69. * Value of 1 is equal to the Yaw angle in radians.
  70. */
  71. public bankedTurnMultiplier: number = 1;
  72. /**
  73. * The inputs manager loads all the input sources, such as keyboard and mouse.
  74. */
  75. public inputs: FlyCameraInputsManager;
  76. /**
  77. * Gets the input sensibility for mouse input.
  78. * Higher values reduce sensitivity.
  79. */
  80. public get angularSensibility(): number {
  81. var mouse = <FlyCameraMouseInput>this.inputs.attached["mouse"];
  82. if (mouse) {
  83. return mouse.angularSensibility;
  84. }
  85. return 0;
  86. }
  87. /**
  88. * Sets the input sensibility for a mouse input.
  89. * Higher values reduce sensitivity.
  90. */
  91. public set angularSensibility(value: number) {
  92. var mouse = <FlyCameraMouseInput>this.inputs.attached["mouse"];
  93. if (mouse) {
  94. mouse.angularSensibility = value;
  95. }
  96. }
  97. /**
  98. * Get the keys for camera movement forward.
  99. */
  100. public get keysForward(): number[] {
  101. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  102. if (keyboard) {
  103. return keyboard.keysForward;
  104. }
  105. return [];
  106. }
  107. /**
  108. * Set the keys for camera movement forward.
  109. */
  110. public set keysForward(value: number[]) {
  111. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  112. if (keyboard) {
  113. keyboard.keysForward = value;
  114. }
  115. }
  116. /**
  117. * Get the keys for camera movement backward.
  118. */
  119. public get keysBackward(): number[] {
  120. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  121. if (keyboard) {
  122. return keyboard.keysBackward;
  123. }
  124. return [];
  125. }
  126. public set keysBackward(value: number[]) {
  127. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  128. if (keyboard) {
  129. keyboard.keysBackward = value;
  130. }
  131. }
  132. /**
  133. * Get the keys for camera movement up.
  134. */
  135. public get keysUp(): number[] {
  136. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  137. if (keyboard) {
  138. return keyboard.keysUp;
  139. }
  140. return [];
  141. }
  142. /**
  143. * Set the keys for camera movement up.
  144. */
  145. public set keysUp(value: number[]) {
  146. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  147. if (keyboard) {
  148. keyboard.keysUp = value;
  149. }
  150. }
  151. /**
  152. * Get the keys for camera movement down.
  153. */
  154. public get keysDown(): number[] {
  155. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  156. if (keyboard) {
  157. return keyboard.keysDown;
  158. }
  159. return [];
  160. }
  161. /**
  162. * Set the keys for camera movement down.
  163. */
  164. public set keysDown(value: number[]) {
  165. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  166. if (keyboard) {
  167. keyboard.keysDown = value;
  168. }
  169. }
  170. /**
  171. * Get the keys for camera movement left.
  172. */
  173. public get keysLeft(): number[] {
  174. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  175. if (keyboard) {
  176. return keyboard.keysLeft;
  177. }
  178. return [];
  179. }
  180. /**
  181. * Set the keys for camera movement left.
  182. */
  183. public set keysLeft(value: number[]) {
  184. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  185. if (keyboard) {
  186. keyboard.keysLeft = value;
  187. }
  188. }
  189. /**
  190. * Set the keys for camera movement right.
  191. */
  192. public get keysRight(): number[] {
  193. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  194. if (keyboard) {
  195. return keyboard.keysRight;
  196. }
  197. return [];
  198. }
  199. /**
  200. * Set the keys for camera movement right.
  201. */
  202. public set keysRight(value: number[]) {
  203. var keyboard = <FlyCameraKeyboardInput>this.inputs.attached["keyboard"];
  204. if (keyboard) {
  205. keyboard.keysRight = value;
  206. }
  207. }
  208. /**
  209. * Event raised when the camera collides with a mesh in the scene.
  210. */
  211. public onCollide: (collidedMesh: AbstractMesh) => void;
  212. private _collider: Collider;
  213. private _needMoveForGravity = false;
  214. private _oldPosition = Vector3.Zero();
  215. private _diffPosition = Vector3.Zero();
  216. private _newPosition = Vector3.Zero();
  217. /** @hidden */
  218. public _localDirection: Vector3;
  219. /** @hidden */
  220. public _transformedDirection: Vector3;
  221. /**
  222. * Instantiates a FlyCamera.
  223. * This is a flying camera, designed for 3D movement and rotation in all directions,
  224. * such as in a 3D Space Shooter or a Flight Simulator.
  225. * @param name Define the name of the camera in the scene.
  226. * @param position Define the starting position of the camera in the scene.
  227. * @param scene Define the scene the camera belongs to.
  228. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active, if no other camera has been defined as active.
  229. */
  230. constructor(name: string, position: Vector3, scene: Scene, setActiveOnSceneIfNoneActive = true) {
  231. super(name, position, scene, setActiveOnSceneIfNoneActive);
  232. this.inputs = new FlyCameraInputsManager(this);
  233. this.inputs.addKeyboard().addMouse();
  234. }
  235. /**
  236. * Attach a control to the HTML DOM element.
  237. * @param element Defines the element that listens to the input events.
  238. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
  239. */
  240. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  241. this.inputs.attachElement(element, noPreventDefault);
  242. }
  243. /**
  244. * Detach a control from the HTML DOM element.
  245. * The camera will stop reacting to that input.
  246. * @param element Defines the element that listens to the input events.
  247. */
  248. public detachControl(element: HTMLElement): void {
  249. this.inputs.detachElement(element);
  250. this.cameraDirection = new Vector3(0, 0, 0);
  251. }
  252. // Collisions.
  253. private _collisionMask = -1;
  254. /**
  255. * Get the mask that the camera ignores in collision events.
  256. */
  257. public get collisionMask(): number {
  258. return this._collisionMask;
  259. }
  260. /**
  261. * Set the mask that the camera ignores in collision events.
  262. */
  263. public set collisionMask(mask: number) {
  264. this._collisionMask = !isNaN(mask) ? mask : -1;
  265. }
  266. /** @hidden */
  267. public _collideWithWorld(displacement: Vector3): void {
  268. var globalPosition: Vector3;
  269. if (this.parent) {
  270. globalPosition = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  271. } else {
  272. globalPosition = this.position;
  273. }
  274. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  275. this._oldPosition.addInPlace(this.ellipsoidOffset);
  276. if (!this._collider) {
  277. this._collider = new Collider();
  278. }
  279. this._collider._radius = this.ellipsoid;
  280. this._collider.collisionMask = this._collisionMask;
  281. // No need for clone, as long as gravity is not on.
  282. var actualDisplacement = displacement;
  283. // Add gravity to direction to prevent dual-collision checking.
  284. if (this.applyGravity) {
  285. // This prevents mending with cameraDirection, a global variable of the fly camera class.
  286. actualDisplacement = displacement.add(this.getScene().gravity);
  287. }
  288. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  289. }
  290. /** @hidden */
  291. private _onCollisionPositionChange = (collisionId: number, newPosition: Vector3, collidedMesh: Nullable<AbstractMesh> = null) => {
  292. var updatePosition = (newPos: Vector3) => {
  293. this._newPosition.copyFrom(newPos);
  294. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  295. if (this._diffPosition.length() > Engine.CollisionsEpsilon) {
  296. this.position.addInPlace(this._diffPosition);
  297. if (this.onCollide && collidedMesh) {
  298. this.onCollide(collidedMesh);
  299. }
  300. }
  301. };
  302. updatePosition(newPosition);
  303. }
  304. /** @hidden */
  305. public _checkInputs(): void {
  306. if (!this._localDirection) {
  307. this._localDirection = Vector3.Zero();
  308. this._transformedDirection = Vector3.Zero();
  309. }
  310. this.inputs.checkInputs();
  311. super._checkInputs();
  312. }
  313. /** @hidden */
  314. public _decideIfNeedsToMove(): boolean {
  315. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  316. }
  317. /** @hidden */
  318. public _updatePosition(): void {
  319. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  320. this._collideWithWorld(this.cameraDirection);
  321. } else {
  322. super._updatePosition();
  323. }
  324. }
  325. /**
  326. * Restore the Roll to its target value at the rate specified.
  327. * @param rate - Higher means slower restoring.
  328. * @hidden
  329. */
  330. public restoreRoll(rate: number): void {
  331. let limit = this._trackRoll; // Target Roll.
  332. let z = this.rotation.z; // Current Roll.
  333. let delta = limit - z; // Difference in Roll.
  334. let minRad = 0.001; // Tenth of a radian is a barely noticable difference.
  335. // If the difference is noticable, restore the Roll.
  336. if (Math.abs(delta) >= minRad) {
  337. // Change Z rotation towards the target Roll.
  338. this.rotation.z += delta / rate;
  339. // Match when near enough.
  340. if (Math.abs(limit - this.rotation.z) <= minRad) {
  341. this.rotation.z = limit;
  342. }
  343. }
  344. }
  345. /**
  346. * Destroy the camera and release the current resources held by it.
  347. */
  348. public dispose(): void {
  349. this.inputs.clear();
  350. super.dispose();
  351. }
  352. /**
  353. * Get the current object class name.
  354. * @returns the class name.
  355. */
  356. public getClassName(): string {
  357. return "FlyCamera";
  358. }
  359. }