关注单指输入:按下、滑动、抬起时,传出手指位置(在UI坐标系中)。
SingleTouchCtr.ts
import { _decorator, Component, Node, input, Input, EventTouch, EventTarget } from 'cc';
const { ccclass, property } = _decorator;
export class SingleTouchCtr
{
private _touchId: number;
private static readonly defaultTouchId = -1;
private _eventTarget: EventTarget;
public get eventTarget(): EventTarget { return this._eventTarget };
public static readonly SingleTouchDownEvent: string = 'SingleTouchDownEvent';
public static readonly SingleTouchMoveEvent: string = 'SingleTouchMoveEvent';
public static readonly SingleTouchUpEvent: string = 'SingleTouchUpEvent';
public constructor()
{
input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
this.resetTouchId();
this._eventTarget = new EventTarget();
}
public myDestroy(): void
{
input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
this._eventTarget = null;
}
private resetTouchId(): void
{
this._touchId = SingleTouchCtr.defaultTouchId;
}
private hasTouchId(): boolean {
return this._touchId != SingleTouchCtr.defaultTouchId;
}
private onTouchStart(event: EventTouch): void
{
if (!this.hasTouchId()) {
this._touchId = event.touch.getID();
this.eventTarget.emit(SingleTouchCtr.SingleTouchDownEvent, event.touch.getUILocation());
}
}
private onTouchMove(event: EventTouch): void
{
if (this._touchId == event.touch.getID()) {
this.eventTarget.emit(SingleTouchCtr.SingleTouchMoveEvent, event.touch.getUILocation());
}
}
private onTouchEnd(event: EventTouch): void
{
if (this._touchId == event.touch.getID()) {
this.eventTarget.emit(SingleTouchCtr.SingleTouchUpEvent, event.touch.getUILocation());
this.resetTouchId();
}
}
}
网友评论