fadeInOutBehavior.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { Behavior } from "../behavior";
  2. import { AbstractMesh } from "../../Meshes/abstractMesh";
  3. import { Mesh } from "../../Meshes/mesh";
  4. import { Nullable } from "../../types";
  5. /**
  6. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  7. */
  8. export class FadeInOutBehavior implements Behavior<Mesh> {
  9. /**
  10. * Time in milliseconds to delay before fading in (Default: 0)
  11. */
  12. public delay = 0;
  13. /**
  14. * Time in milliseconds for the mesh to fade in (Default: 300)
  15. */
  16. public fadeInTime = 300;
  17. private _millisecondsPerFrame = 1000 / 60;
  18. private _hovered = false;
  19. private _hoverValue = 0;
  20. private _ownerNode: Nullable<Mesh> = null;
  21. /**
  22. * Instantiates the FadeInOutBehavior
  23. */
  24. constructor() {
  25. }
  26. /**
  27. * The name of the behavior
  28. */
  29. public get name(): string {
  30. return "FadeInOut";
  31. }
  32. /**
  33. * Initializes the behavior
  34. */
  35. public init() {
  36. }
  37. /**
  38. * Attaches the fade behavior on the passed in mesh
  39. * @param ownerNode The mesh that will be faded in/out once attached
  40. */
  41. public attach(ownerNode: Mesh): void {
  42. this._ownerNode = ownerNode;
  43. this._setAllVisibility(this._ownerNode, 0);
  44. }
  45. /**
  46. * Detaches the behavior from the mesh
  47. */
  48. public detach(): void {
  49. this._ownerNode = null;
  50. }
  51. /**
  52. * Triggers the mesh to begin fading in or out
  53. * @param value if the object should fade in or out (true to fade in)
  54. */
  55. public fadeIn(value: boolean) {
  56. this._hovered = value;
  57. this._update();
  58. }
  59. private _update = () => {
  60. if (this._ownerNode) {
  61. this._hoverValue += this._hovered ? this._millisecondsPerFrame : -this._millisecondsPerFrame;
  62. this._setAllVisibility(this._ownerNode, (this._hoverValue - this.delay) / this.fadeInTime);
  63. if (this._ownerNode.visibility > 1) {
  64. this._setAllVisibility(this._ownerNode, 1);
  65. this._hoverValue = this.fadeInTime + this.delay;
  66. return;
  67. } else if (this._ownerNode.visibility < 0) {
  68. this._setAllVisibility(this._ownerNode, 0);
  69. if (this._hoverValue < 0) {
  70. this._hoverValue = 0;
  71. return;
  72. }
  73. }
  74. setTimeout(this._update, this._millisecondsPerFrame);
  75. }
  76. }
  77. private _setAllVisibility(mesh: AbstractMesh, value: number) {
  78. mesh.visibility = value;
  79. mesh.getChildMeshes().forEach((c) => {
  80. this._setAllVisibility(c, value);
  81. });
  82. }
  83. }