引擎版本 3.4.1
脚本组件,挂载即用
ClickPenetrate.ts
import * as cc from 'cc';
import { _decorator, Component, Button, SystemEvent } from 'cc';
const { ccclass, property } = _decorator;
/**
* 按钮 点击穿透
* @author 神兽白泽
*/
@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<cc.EventHandler> = [];
@property({ tooltip: "触摸移动", type: cc.EventHandler })
private on_touch_move: Array<cc.EventHandler> = [];
@property({ tooltip: "触摸结束", type: cc.EventHandler })
private on_touch_end: Array<cc.EventHandler> = [];
// @property({ tooltip: "触摸关闭", type: cc.EventHandler })
// private on_touch_cancel: Array<cc.EventHandler> = [];
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(SystemEvent.EventType.TOUCH_START, this.onTouchBegan, this);
this.comp_btn.node.on(SystemEvent.EventType.TOUCH_MOVE, this.onTouchMoved, this);
this.comp_btn.node.on(SystemEvent.EventType.TOUCH_END, this.onTouchEnded, this);
this.comp_btn.node.on(SystemEvent.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;
}
}
属性检查器
整理不易,关注收藏不迷路。
目录:CocosCreator经典笔记_神兽白泽-CSDN博客
笔者qq、微信:1302109196
qq群:415468592
|