Files
heros/assets/script/game/common/EnhancedButtonTouchLong.ts
2025-06-26 10:49:08 +08:00

102 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { EventHandler, EventTouch, _decorator } from "cc";
import { ButtonTouchLong } from "../../../../extensions/oops-plugin-framework/assets/libs/gui/button/ButtonTouchLong";
const { ccclass, property, menu } = _decorator;
/**
* 增强版长按按钮组件
* 支持长按触发和放开后触发两种事件
*/
@ccclass("EnhancedButtonTouchLong")
@menu('ui/button/EnhancedButtonTouchLong')
export class EnhancedButtonTouchLong extends ButtonTouchLong {
@property({
type: [EventHandler],
tooltip: "放开后触发的事件"
})
releaseEvents: EventHandler[] = [];
@property({
tooltip: "是否在长按后放开时触发事件"
})
triggerOnRelease: boolean = true;
@property({
tooltip: "是否在短按时也触发放开事件"
})
triggerOnShortPress: boolean = false;
private _wasLongPressed: boolean = false;
private _hasTriggeredRelease: boolean = false;
onLoad() {
super.onLoad();
this._wasLongPressed = false;
this._hasTriggeredRelease = false;
}
/** 触摸开始 */
onTouchtStart(event: EventTouch) {
this._wasLongPressed = false;
this._hasTriggeredRelease = false;
super.onTouchtStart(event);
}
/** 触摸结束 */
onTouchEnd(event: EventTouch) {
// 检查是否已经长按过
if (this._passTime > this.time) {
this._wasLongPressed = true;
}
// 触发放开事件
if (this.triggerOnRelease && !this._hasTriggeredRelease) {
if (this._wasLongPressed || this.triggerOnShortPress) {
this._hasTriggeredRelease = true;
this.onReleaseTrigger();
}
}
super.onTouchEnd(event);
}
/** 引擎更新事件 */
update(dt: number) {
super.update(dt);
// 在父类的update中如果触发了长按事件标记为已长按
if (this._passTime >= this.time && !this._isTouchLong) {
this._wasLongPressed = true;
}
}
/**
* 放开触发回调
*/
protected onReleaseTrigger() {
// 发送自定义事件
this.node.emit('releaseTrigger', this);
// 触发配置的事件
this.releaseEvents.forEach(event => {
event.emit([event.customEventData]);
});
console.log('放开触发!');
}
/**
* 获取是否已经长按过
*/
wasLongPressed(): boolean {
return this._wasLongPressed;
}
/**
* 获取当前按住时间
*/
getPassTime(): number {
return this._passTime;
}
}