fadeInOutBehavior.ts 2.9 KB

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