进度条控制脚本,支持节点进度条,图片进度条,进度条组件,和进度文字展示
const { ccclass, property, menu } = cc._decorator;
let text_type = cc.Enum({
"20%": 0,
"1/5": 1,
"差值": 2,
"自定义": 3,
});
let bar_type = cc.Enum({
"Sprite": 0,
"ProgressBar": 1,
"Node": 2,
});
@ccclass
@menu("自定义组件/进度条")
export default class barNode extends cc.Component {
@property({
type: cc.Sprite,
visible() { return this.barType == bar_type.Sprite }
})
spriteBar: cc.Sprite = null;
@property({
type: cc.ProgressBar,
visible() { return this.barType == bar_type.ProgressBar }
})
progressBar: cc.ProgressBar = null;
@property({
type: cc.Node,
visible() { return this.barType == bar_type.Node }
})
nodeBar: cc.Node = null;
@property({
type: cc.Float,
visible() { return this.barType == bar_type.Node }
})
max: number = 1;
@property({
type: cc.Float,
visible() { return this.barType == bar_type.Node }
})
min: number = 0;
@property(cc.RichText)
barDesc: cc.RichText = null;
@property(cc.Label)
barDesc2: cc.Label = null;
@property({
type: cc.Enum(bar_type),
displayName: "进度条类型"
})
barType = bar_type.Sprite;
@property({
type: cc.Enum(text_type),
displayName: "进度文字类型"
})
textType = text_type["1/5"];
_width = 0;
protected onLoad(): void {
}
init(value, limit, bar_desc?) {
let desc: string = bar_desc || "[0]";
let percent = value / limit;
percent = percent > 1 ? 1 : percent;
if (this.spriteBar && this.barType == bar_type.Sprite) this.spriteBar.fillRange = percent;
if (this.progressBar && this.barType == bar_type.ProgressBar) this.progressBar.progress = (percent < 0.1 && percent != 0) ? 0.1 : percent;
if (this.nodeBar && this.barType == bar_type.Node) {
this.nodeBar.width = (percent && percent * this.max < this.min) ? this.min : percent * this.max;
}
let str = "";
switch (this.textType) {
case 0: str = `${this.fixForce(percent * 100, 2)}%`
desc = desc.replace("[0]", str);
break;
case 1: str = `${value}/${limit}`;
desc = desc.replace("[0]", str);
break;
case 2: str = `${limit - value < 0 ? 0 : limit - value}`
desc = desc.replace("[0]", str);
break;
case 3:
desc = desc.replace("[0]", value);
desc = desc.replace("[1]", limit);
break;
}
if (this.barDesc) this.barDesc.string = desc;
if (this.barDesc2) this.barDesc2.string = desc;
}
fixForce(count, fixTo): string {
let a = (count + "").split(".");
let b = a[0];
if (a.length > 1) b = a[0] + "." + a[1].slice(0, fixTo);
if (b == "0.00" && count != 0) {
if (a.length > 1) b = a[0] + "." + a[1].slice(0, 4);
}
return b;
}
}