又来一款打字机,简单吧!

    技术2022-07-10  147

    点击上方蓝色字体,关注我们

    打字机,文字逐个出现,应该是很多游戏中用到的功能吧!比如新手引导,需要有文字对话,文字一个一个显示出来。我在这里用Cocos Creator做了个简单的组件和demo。效果如下图。

    1

    上代码 const {ccclass, property} = cc._decorator; @ccclass export default class TypeWriter extends cc.Component { @property(cc.Label) label: cc.Label = null; @property text: string = ''; @property({ tooltip:"打字机打字的时间间隔(ms)", }) duration: number = 100; start () { // init logic let strLen = this.text.length; let content = this.text.split(""); let curStr = ""; let self = this; for(let i = 0; i < strLen; i++){ setTimeout(()=>{ curStr += content[i]; self.label.string = curStr; },self.duration*(i)); } } }

    2

    讲解

    本段组件代码使用Typescript编写,TypeWriter继承cc.Component,其中有两个属性,一个cc.Label的节点,用于显示文本。一个适用于存放显示内容的字符串。在demo中,就是如上图的Cocos Creator做游戏真是简单··· 还有字符播放间隔是300ms。也就是每隔0.3s播放一个字符。

    实现思路就是将字符串切割为单个字符,然后每隔300ms,追加一个字符到一个新的字符串变量,再把新的字符串变量设置为Label的string,即可。代码如上图。

    在这里,我使用的是setTimeout做延时。

    end

    我是小周,一名移动开发程序员。每天学习一点点,从小白到大牛,并非遥不可及。加油!

    如有错误,还请指出,一起学习,一起进步!感谢你的关注~

    Processed: 0.011, SQL: 9