cocoscreator按钮长按功能实现

背景

产品需要游戏的开始按钮,单击:游戏开始;长按:显示托管场次面板。
引擎:cocoscretor v2.1.2 语言:JavaScript

实现

cc.Class({
    extends: cc.Component,

    properties: {
        btnStart: cc.Button,                //开始按钮
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        //声明触摸时间变量
        this.touchFlag = false;
        this.touchStartTime = null;
        //添加按钮触摸监听 长按弹托管弹窗列表
        this.btnStart.node.on(cc.Node.EventType.TOUCH_START, this.touchStart, this);
        this.btnStart.node.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this);
    },

    // start () {},

    // onEnable() {},

    //触摸开始
    touchStart(){
        //触摸开始 
        this.touchFlag = true;
        //记录下触摸开始时间
        this.touchStartTime = new Date();
    },

    //长按检测函数
    touchHold(){
        if(this.touchFlag && this.touchStartTime != null){
            //判断按钮的按压时长
            let touchHoldTime = new Date();
            let milliseconds = touchHoldTime.getTime() - this.touchStartTime.getTime();
            if(milliseconds > 300){
                this.touchFlag = false;
                //触发托管事务逻辑 
                //todo...
            }
        }
    },

    //触摸结束
    touchEnd(){
        this.touchFlag = false;
        this.touchStartTime = null;
        //出发单击事务逻辑
        //todo...
    },

    update (dt) {
        //判断是否检测按钮长按状态
        if(this.touchFlag){
            this.touchHold();
        }
    },
});

备注:因为cocoscretor留下的按钮监听事件中的 cc.Node.EventType.MOUSE_MOVE,在触摸点未发生任何像素上的移动时,是不会触发该此事件监听函数的。所以,本文采取了touchFlag变量和update函数配合的方式来实现业务上的需求。
核心:监听节点按下、抬起事件,通过比较两个事件之间的时间差,来进行单机、长按判断。
至此,完毕。

猜你喜欢

转载自blog.csdn.net/qq_41973169/article/details/130384356
今日推荐