DialogueManager.ts 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import { _decorator, Component, Node, Label, Tween, tween, Vec3, UITransform } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('DialogueManager')
  4. export class DialogueManager extends Component {
  5. @property({
  6. type: Node,
  7. tooltip: '对话框节点'
  8. })
  9. dialogueNode: Node = null;
  10. @property({
  11. type: Label,
  12. tooltip: '显示对话内容的文本标签'
  13. })
  14. dialogueLabel: Label = null;
  15. @property({
  16. tooltip: '对话框弹出动画持续时间(秒)'
  17. })
  18. popupDuration: number = 0.3;
  19. @property({
  20. tooltip: '对话框缩放前的初始大小(比例)'
  21. })
  22. initialScale: number = 0.5;
  23. @property({
  24. tooltip: '对话框最终大小(比例)'
  25. })
  26. targetScale: number = 1.0;
  27. private currentDialogue: string = '';
  28. private dialogueAnimation: Tween<Node> = null;
  29. start() {
  30. // 确保对话框初始隐藏
  31. if (this.dialogueNode) {
  32. this.dialogueNode.active = false;
  33. }
  34. }
  35. /**
  36. * 显示新对话
  37. * @param text 对话内容,如果为空则重复当前对话
  38. */
  39. public showDialogue(text: string = ''): void {
  40. // 如果传入的文本为空,则使用当前对话
  41. const dialogueText = text || this.currentDialogue;
  42. // 如果对话为空,则不执行任何操作
  43. if (!dialogueText) {
  44. return;
  45. }
  46. // 保存当前对话文本
  47. this.currentDialogue = dialogueText;
  48. // 设置对话内容
  49. if (this.dialogueLabel) {
  50. this.dialogueLabel.string = dialogueText;
  51. }
  52. // 显示对话框并播放弹出动画
  53. this.playPopupAnimation();
  54. }
  55. /**
  56. * 播放对话框弹出动画
  57. */
  58. private playPopupAnimation(): void {
  59. if (!this.dialogueNode) {
  60. return;
  61. }
  62. // 停止正在播放的动画(如果有)
  63. if (this.dialogueAnimation) {
  64. this.dialogueAnimation.stop();
  65. }
  66. // 显示对话框
  67. this.dialogueNode.active = true;
  68. // 设置初始缩放
  69. this.dialogueNode.setScale(new Vec3(this.initialScale, this.initialScale, 1));
  70. // 创建弹出动画
  71. this.dialogueAnimation = tween(this.dialogueNode)
  72. .to(this.popupDuration, { scale: new Vec3(this.targetScale, this.targetScale, 1) }, {
  73. easing: 'elasticOut'
  74. })
  75. .start();
  76. }
  77. /**
  78. * 隐藏对话框
  79. */
  80. public hideDialogue(): void {
  81. if (this.dialogueNode) {
  82. // 停止正在播放的动画(如果有)
  83. if (this.dialogueAnimation) {
  84. this.dialogueAnimation.stop();
  85. }
  86. // 隐藏对话框并重置缩放
  87. this.dialogueNode.active = false;
  88. this.dialogueNode.setScale(new Vec3(this.initialScale, this.initialScale, 1));
  89. }
  90. }
  91. /**
  92. * 判断对话框是否正在显示
  93. */
  94. public isDialogueShowing(): boolean {
  95. return this.dialogueNode ? this.dialogueNode.active : false;
  96. }
  97. }