[开源] 控制任意节点下单点触摸singleTouch

原位置在这

挺好用的,我一直在用,放个显眼的位置


用法

新建个TS脚本,将代码粘贴进去,想让哪个节点下(包括其祖孙节点)是单点触摸,就把这个组件挂到哪个节点上,很适合那种需要多点触摸,但个别位置需要单点控制的情况


const { ccclass } = cc._decorator;

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

    private _touchStart(event) {
        if (this._touchID !== null) {
            event.stopPropagation();
        } else {
            this._touchID = event.getID();
        }
    }

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

    private _touchEnd(event) {
        if (this._touchID !== event.getID()) {
            event.stopPropagation();
        } else if (!event.simulate) {
            this._touchID = null;
        }
    }

    onEnable() {
        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);
    }

    onDisable() {
        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);
    }
}
3赞