import * as cc from 'cc'; import { _decorator, Component, Button, Input } from 'cc'; const { ccclass, property } = _decorator; /*** 按钮 点击穿透*/ @ccclass('ClickPenetrate') export class ClickPenetrate extends Component { @property({ tooltip: "滑动会关闭 end 触摸事件" }) private move_began_end: boolean = false; @property({ tooltip: "触摸开始", type: cc.EventHandler }) private on_touch_began: Array = []; @property({ tooltip: "触摸移动", type: cc.EventHandler }) private on_touch_move: Array = []; @property({ tooltip: "触摸结束", type: cc.EventHandler }) private on_touch_end: Array = []; // @property({ tooltip: "触摸关闭", type: cc.EventHandler }) // private on_touch_cancel: Array = []; private has_began: boolean = false; private comp_btn: cc.Button = null; onLoad() { this.comp_btn = this.node.getComponent(cc.Button) || this.node.addComponent(cc.Button); this.comp_btn.node.on(Input.EventType.TOUCH_START, this.onTouchBegan, this); this.comp_btn.node.on(Input.EventType.TOUCH_MOVE, this.onTouchMoved, this); this.comp_btn.node.on(Input.EventType.TOUCH_END, this.onTouchEnded, this); this.comp_btn.node.on(Input.EventType.TOUCH_CANCEL, this.onTouchCancelled, this); } private onTouchBegan(touch: cc.EventTouch, param: any): void { touch.preventSwallow = true;this.has_began = true; this.is_move = false;this.delta = new cc.Vec2(0, 0); this.on_touch_began.forEach((value, key) => { value.emit([this.comp_btn]) }) } /** 是移动状态 */ private is_move = null; /** 本次点击所移动的距离 */ private delta: cc.Vec2 = new cc.Vec2(0, 0); private onTouchMoved(touch: cc.EventTouch, param: any): void { touch.preventSwallow = true; if (!this.has_began) return; this.on_touch_move.forEach((value, key) => { value.emit([this.comp_btn]) }) let delta = touch.getDelta(); this.delta.x += delta.x; this.delta.y += delta.y; const distance = this.delta.length(); if (distance >= 20) this.is_move = true; // 滑动超过20像素,算作点击 } private onTouchEnded(touch: cc.EventTouch, param: any): void { touch.preventSwallow = true; if (!this.has_began) return; if (this.move_began_end && this.is_move) return; this.on_touch_end.forEach((value, key) => { value.emit([this.comp_btn]) }) this.has_began = false; this.is_move = false; } private onTouchCancelled(touch: cc.EventTouch, param: any): void { touch.preventSwallow = true; } }