點擊上方藍色字體,關注我們
打字機,文字逐個出現,應該是很多遊戲中用到的功能吧!比如新手引導,需要有文字對話,文字一個一個顯示出來。我在這裏用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
我是小周,一名移動開發程序員。每天學習一點點,從小白到大牛,並非遙不可及。加油!
如有錯誤,還請指出,一起學習,一起進步!感謝你的關注~