Cocos Creator個性化時間進(jìn)度條實現(xiàn)
在Cocos Creator游戲開發(fā)中,經(jīng)常需要使用個性化時間進(jìn)度條,下面,我們就一起來封裝下自己的個性化時間進(jìn)度條組件。
一、 個性化時間進(jìn)度條
1: ?編寫腳本, 來使用sprite的扇形來顯示當(dāng)前的進(jìn)度:
屬性: time_sec: 定時器的時間
clockwise: 是否為順時針或逆時針;
reverse: ?是否反轉(zhuǎn)
startClockAction: 開始累積時間,看時間過去的百分比,來改變精靈顯示的百分比;
stopClockAction: 停止計時累積;
二、 計時器控制組件
const {ccclass, property} = cc._decorator;
@ccclass
export default class ClockCtrl extends cc.Component {
? ?@property({tooltip:"計時時長"})
? ?actionTime : number = 10;
? ?@property({tooltip:"是否逆時針"})
? ?clockWise : boolean = false;
? ?@property({tooltip:"計時方向"})
? ?reverse : boolean = false; ?// false,由少變多
? ?@property({tooltip:"是否在加載的時候就開始計時"})
playOnLoad : boolean = false;
private nowTime : number = 0; ? // 用于記錄已經(jīng)過去的時間
private isRuning : boolean = false; // 計時器是否正在行走
private sprite : cc.Sprite;
private endFunc : Function = null;
onLoad () {
this.node.active = false;
// 獲取子節(jié)點上的Sprite組件
this.sprite = this.node.getChildByName("TimerBar").getComponent(cc.Sprite);
if(this.playOnLoad){
this.startClockAction(this.actionTime, this.endFunc);
? ? ? ?}
}
startClockAction(actionTime : number, endFunc : Function){
if(actionTime <= 0){
return;
? ? ? ?}
this.endFunc = endFunc;
this.node.active = true;
this.actionTime = actionTime;
this.nowTime = 0;
this.isRuning = true;
}
stopClockAction(){
this.node.active = false;
this.isRuning = false;
}
update (dt : number) {
if(!this.isRuning){
return;
? ? ? ?}
this.nowTime += dt;
// 將時間轉(zhuǎn)換為百分比,設(shè)置給this.sprite的FillRange屬性
let per : number = this.nowTime/this.actionTime;
if(per > 1){
? ? ? ? ? ?per = 1;
this.isRuning = false;
if(this.endFunc){
this.endFunc();
? ? ? ? ? ?}
? ? ? ?}
// 進(jìn)度條 由多變少的控制
// per : 0 ?0.5 1
// 1-per:1 ?0.5 0
if(this.reverse){
? ? ? ? ? ?per = 1 - per;
? ? ? ?}
// 順時針和逆時針的控制
if(this.clockWise){
? ? ? ? ? ?per = -per;
? ? ? ?}
this.sprite.fillRange = per;
? ?}
}
三、 UI組件

四、 組件的使用測試GameMgr.ts
import ClockCtrl from "./ClockCtrl";
const {ccclass, property} = cc._decorator;
@ccclass
export default class GameMgr extends cc.Component { ? ?
? ?@property({type:ClockCtrl, tooltip:"計時器組件"})
? ?clock : ClockCtrl = null;
? ?@property({tooltip:"計時器計時時長"})
? ?actionTime : number = 5;
private endFunc(){
console.log(this.actionTime,"秒倒計時完成!");
? ?}
start(){
this.clock.startClockAction(this.actionTime, this.endFunc);
}
}

