分享一个Creator v2.2的单点触摸

⚠️在Creator V2.4中,官方已经提供了屏蔽多点触摸事件的方法:cc.macro.ENABLE_MULTI_TOUCH = false;


代码如下:


const { ccclass } = cc._decorator;

@ccclass
export default class SingleTouch extends cc.Component {
    private _touchID: number = null;
    private bActive = false;

    onLoad() {
        this.singleTouch();
    }

    onDestroy() {
        this.resumeTouch();
    }


    singleTouch() {
        if (this.bActive) return;
        console.log('singleTouch');
        this.bActive = true;
        this.node.on(cc.Node.EventType.TOUCH_START, this._touchStart, this, true);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this._touchMove, this, true);
        this.node.on(cc.Node.EventType.TOUCH_END, this._touchEnd, this, true);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._touchEnd, this, true);
    }
    resumeTouch() {
        if (!this.bActive) return;
        console.log('resumeTouch');
        this.bActive = false;
        this.node.off(cc.Node.EventType.TOUCH_START, this._touchStart, this, true);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this._touchMove, this, true);
        this.node.off(cc.Node.EventType.TOUCH_END, this._touchEnd, this, true);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._touchEnd, this, true);
    }

    private _touchStart(event: cc.Event.EventTouch) {
        // 有效性检查
        if (this._touchID !== null) {
            const index = window._cc.inputManager._touchesIntegerDict[this._touchID];
            if (index === undefined) {
                this._touchID = null;
                console.log('_touchStart: 强制this._touchID = null');
            }
        }


        if (this._touchID === null || this._touchID === event.getID()) {
            this._touchID = event.getID();
            // console.log('_touchStart: this._touchID', this._touchID);
        } else {
            event.stopPropagation();
            console.warn('_touchStart: event.stopPropagation()', event.getID());
        }
    }

    private _touchMove(event) {
        if (this._touchID !== event.getID()) {
            event.stopPropagation();
        }
    }

    private _touchEnd(event) {
        if (this._touchID === null) {
            console.warn('_touchEnd: this._touchID === null', event.getID());
        } else {
            if (this._touchID !== event.getID()) {
                event.stopPropagation();
                console.warn('_touchEnd:  this._touchID !== event.getID()', this._touchID, event.getID());
            } else if (!event.simulate)  {
                this._touchID = null;
                // console.log('_touchEnd: this._touchID = null');
            }
        }
    }
}

将脚本添加到场景根节点上即可生效。


更多文章
个人博客: https://blog.csdn.net/u014560101
公众号:游戏开发之旅
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值