cocos creator 3.6.2 实现自定义进度条

911 阅读1分钟

一、实现一个竖向/横向进度条

1、在场景中添加sprite,修改sprite的填充方式(fill type)为VERTICAL(竖向)或者HORIZONTAL(横向),也就是添加一个满进度条的图片,通过改变图片的填充方式来实现进度的变化

2、在脚本中

import { _decorator, Component, Node, Sprite, find, Label } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('ProgressBar')
export class ProgressBar extends Component {
    totalSecond: number = 15 // 总秒数
    countSecond: number = this.totalSecond;
    startSecond: number = 0;

    start() {
        this.countDownProgress();
        this.countUpProgress();
    }
    /**
     * 倒计时版
     * 在场景中fill range 初始值需设为1
     */
    countDownProgress() {
        let progressBar = this.node.getComponent(Sprite);
        let timer = setInterval(() => {
            progressBar.fillRange = (this.countSecond / this.totalSecond);
            this.countSecond -= 1;
            if (this.countSecond <= 0) {
                progressBar.fillRange = 0;
                clearInterval(timer);
                console.log("定时器已清除");
            }
        }, 1000)
    }
    /**
     * 正计时版
     * 在场景中fill range 初始值需设为0
     */
    countUpProgress() {
        let progressBar = this.node.getComponent(Sprite);
        let timer = setInterval(() => {
            progressBar.fillRange = (this.startSecond / this.totalSecond);
            this.startSecond += 1;
            if (this.startSecond >= this.totalSecond) {
                progressBar.fillRange = 1;
                clearInterval(timer);
                console.log("定时器已清除");
            }
        }, 1000)
    }

    update(deltaTime: number) {

    }

}

二、实现圆形进度条

1、修改sprite的填充方式为RADIAL

2、修改 fill center 为 x:0.5 y:0.5 ,让圆心在正中间

3、脚本中代码同上,通过修改fill range改变进度条进度