美文网首页
CocosCreator中,单指触屏输入

CocosCreator中,单指触屏输入

作者: 全新的饭 | 来源:发表于2022-11-03 15:47 被阅读0次

    关注单指输入:按下、滑动、抬起时,传出手指位置(在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();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:CocosCreator中,单指触屏输入

          本文链接:https://www.haomeiwen.com/subject/vkdetdtx.html