游戏开发之——对话系统(CocosCreator)

看代码(Typescript):

import { AnalyzeJSON } from "./AnalyzeJSON";

const {ccclass, property} = cc._decorator;

@ccclass
export class Dialog extends cc.Component {

  @property({type:cc.Float, tooltip:"播放速度"})
  playSpeed:number = 0;
  _speed:number;

  
  _dialogLabel:cc.Label = null;    //文本框
  _contentStr:string = "";      //当前播放的内容
  _currTextIndex:number = 0;     //当前播放内容的索引
  _currDialogIndex:number = 0;    //当前对话列表的索引
  _isPlaying:boolean = false;     //是否正在播放
  
  _contentList:Array<string> = null; //谈话内容

  _endEvent:Function = null;     //结束处理事件

  onLoad () {
    this._dialogLabel = this.node.getComponentInChildren(cc.Label);
    this.node.on(cc.Node.EventType.TOUCH_END, this._onClickBox, this);
  }

  /**点击跳过打字机效果 */
  _onClickBox():void{
    if(this._isPlaying){
      this._dialogLabel.string = this._contentStr;
      this._reset();
    }else{
      //对话是否结束 TODO
      this._currDialogIndex++;
      if(this._contentList[this._currDialogIndex] == null)
        this._currDialogIndex = 0;
      this.playDialog(this._contentList[this._currDialogIndex]);
    }
  }

  start () {
    this._speed = this.playSpeed;
    this._contentList = AnalyzeJSON._instance.getDialog();  //从管理器里读取要显示的对话
    this.playDialog(this._contentList[this._currDialogIndex]);
  }

  update (dt) {
    //#region 打字机效果
    if(this._isPlaying){
      this._speed -= dt;
      if(this._speed <= 0){
        this._speed = this.playSpeed;
        if(this._contentStr[this._currTextIndex] == null){
          this._reset();
        }else{
          this._addText(this._contentStr[this._currTextIndex]);
          this._currTextIndex++;
        }
      }else return;
    }
    //#endregion
  }

  /**开始对话 */
  playDialog(str:string, callback?:Function):void{
    this._isPlaying = true;
    this._contentStr = str;
    this._clearContent();
    
    if(callback)
      this._endEvent = callback;
  }

  /**设置速度 */
  setSpeed(val:number):void{
    this.playSpeed = val;
  }


  /**重置内容 */
  _reset():void{
    this._isPlaying = false;
    this._contentStr = "";
    this._currTextIndex = 0;
    this._speed = this.playSpeed;
  }

  /**清除对话框内容 */
  _clearContent():void{
    this._dialogLabel.string = "";
  }

  /**添加文字 */
  _addText(aStr:string):void{
    this._dialogLabel.string += aStr;
  }
}