⚠️
在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
公众号:游戏开发之旅