ClickPenetrate.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import * as cc from 'cc';
  2. import { _decorator, Component, Button, Input } from 'cc';
  3. const { ccclass, property } = _decorator;
  4. /*** 按钮 点击穿透*/
  5. @ccclass('ClickPenetrate')
  6. export class ClickPenetrate extends Component {
  7. @property({ tooltip: "滑动会关闭 end 触摸事件" })
  8. private move_began_end: boolean = false;
  9. @property({ tooltip: "触摸开始", type: cc.EventHandler })
  10. private on_touch_began: Array<cc.EventHandler> = [];
  11. @property({ tooltip: "触摸移动", type: cc.EventHandler })
  12. private on_touch_move: Array<cc.EventHandler> = [];
  13. @property({ tooltip: "触摸结束", type: cc.EventHandler })
  14. private on_touch_end: Array<cc.EventHandler> = [];
  15. // @property({ tooltip: "触摸关闭", type: cc.EventHandler })
  16. // private on_touch_cancel: Array<cc.EventHandler> = [];
  17. private has_began: boolean = false;
  18. private comp_btn: cc.Button = null;
  19. onLoad() {
  20. this.comp_btn = this.node.getComponent(cc.Button) || this.node.addComponent(cc.Button);
  21. this.comp_btn.node.on(Input.EventType.TOUCH_START, this.onTouchBegan, this);
  22. this.comp_btn.node.on(Input.EventType.TOUCH_MOVE, this.onTouchMoved, this);
  23. this.comp_btn.node.on(Input.EventType.TOUCH_END, this.onTouchEnded, this);
  24. this.comp_btn.node.on(Input.EventType.TOUCH_CANCEL, this.onTouchCancelled, this);
  25. }
  26. private onTouchBegan(touch: cc.EventTouch, param: any): void {
  27. touch.preventSwallow = true;this.has_began = true;
  28. this.is_move = false;this.delta = new cc.Vec2(0, 0);
  29. this.on_touch_began.forEach((value, key) => { value.emit([this.comp_btn]) })
  30. }
  31. /** 是移动状态 */
  32. private is_move = null;
  33. /** 本次点击所移动的距离 */
  34. private delta: cc.Vec2 = new cc.Vec2(0, 0);
  35. private onTouchMoved(touch: cc.EventTouch, param: any): void {
  36. touch.preventSwallow = true;
  37. if (!this.has_began) return;
  38. this.on_touch_move.forEach((value, key) => { value.emit([this.comp_btn]) })
  39. let delta = touch.getDelta();
  40. this.delta.x += delta.x;
  41. this.delta.y += delta.y;
  42. const distance = this.delta.length();
  43. if (distance >= 20) this.is_move = true;
  44. // 滑动超过20像素,算作点击
  45. }
  46. private onTouchEnded(touch: cc.EventTouch, param: any): void {
  47. touch.preventSwallow = true;
  48. if (!this.has_began) return;
  49. if (this.move_began_end && this.is_move) return;
  50. this.on_touch_end.forEach((value, key) => { value.emit([this.comp_btn]) })
  51. this.has_began = false;
  52. this.is_move = false;
  53. }
  54. private onTouchCancelled(touch: cc.EventTouch, param: any): void {
  55. touch.preventSwallow = true;
  56. }
  57. }