Cocos Creator 打字机,简单吧!

1.简介

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

2.上代码 

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));
        }
        
    }
}

3.讲解

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

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

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

发布了10 篇原创文章 · 获赞 13 · 访问量 582

猜你喜欢

转载自blog.csdn.net/CoderXZ/article/details/105615200