Cocos Creater 自定义倒计时

最近游戏里需要一个道具倒计时的功能提供玩家可以和道具持续时间的交互,于是记录下,方便以后查看

进度条UI制作

首先进度条只是个普通的样式,直接拿Photoshop画了个圆角矩形,给了无填充和20px边.

在这里插入图片描述

加入组件

注意这里Type要选择Filled,这样之后才能使用后面的根据百分比绘制
在这里插入图片描述
当然图片给了一点opacity,要不然太亮了。

Code

接下来就是代码块了,实现了代码,只用在启用的时候call 一下startCountDown()就可以了。

// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class CountDown extends cc.Component {

    public countDownTime: number = 13; // second
    private sprite: cc.Sprite;
    private isStart: boolean = false;
    private nowTime: number;
    private callback: Function;
    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this.sprite = this.node.getComponent(cc.Sprite);
    }

    public startCountDown(countDownTime: number, callback: Function) {
        this.countDownTime = !!countDownTime ? countDownTime / 1000 : this.countDownTime;
        this.node.active = true;
        this.nowTime = 0;
        this.callback = callback;
        this.isStart = true;

    }
    update(dt) {
        if (!this.isStart) {
            return;
        }

        this.nowTime += dt;
        let per: number = this.nowTime / this.countDownTime;
        if (per > 1) {
            per = 1;
            this.isStart = false;
            this.node.active = false;
            if (!!this.callback) {
                this.callback();
            }
        }
        this.sprite.fillRange = (1 - per);
    }
}


版权声明:本文为Damien_J_Scott原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。