import { SyncEvent } from "ts-events" ; import { Vector2 } from "../math/Vector2" ; export interface KeyEvent { pressed : boolean ; keyCode : number ; } export interface TouchEvent { pressed : boolean ; x : number ; y : number ; swipe : boolean ; swipeVelocity : Vector2 ; button : number ; } namespace Private { export const swipeThreshold = 20 ; export const keyEvent = { pressed : false , keyCode : 0 } ; export const touchEvent = { pressed : false , x : 0 , y : 0 , swipe : false , swipeVelocity : new Vector2 ( ) , button : 0 } ; export const initialTouchPos = new Vector2 ( ) ; } export class Input { static get touchX ( ) { return Private . touchEvent . x ; } static get touchY ( ) { return Private . touchEvent . y ; } static set touchX ( touchX ) { Private . touchEvent . x = touchX ; } static set touchY ( touchY ) { Private . touchEvent . y = touchY ; } static touchPressed = new SyncEvent < TouchEvent > ( ) ; static touchMoved = new SyncEvent < TouchEvent > ( ) ; static touchReleased = new SyncEvent < TouchEvent > ( ) ; static wheelMoved = new SyncEvent < number > ( ) ; static keyChanged = new SyncEvent < KeyEvent > ( ) ; static detachAll ( ) { Input . touchPressed . detach ( ) ; Input . touchMoved . detach ( ) ; Input . touchReleased . detach ( ) ; Input . wheelMoved . detach ( ) ; Input . keyChanged . detach ( ) ; } } hidden export class InputInternal { static create ( touchPos ) { Private . touchEvent . x = touchPos . x ; Private . touchEvent . y = touchPos . y ; } static get keyChangedInfo ( ) { return Private . keyEvent ; } static onTouchDown ( x , y , button ) { if ( x < 0 || y < 0 ) { return ; } Private . touchEvent . pressed = true ; Private . touchEvent . swipe = false ; Private . touchEvent . x = x ; Private . touchEvent . y = y ; Private . touchEvent . button = button ; Private . initialTouchPos . set ( x , y ) ; Input . touchPressed . post ( Private . touchEvent ) ; } static onTouchMove ( x , y , button ) { if ( x < 0 || y < 0 ) { return ; } Private . touchEvent . swipe = false ; Private . touchEvent . x = x ; Private . touchEvent . y = y ; Private . touchEvent . button = button ; Input . touchMoved . post ( Private . touchEvent ) ; } static onTouchUp ( x , y , button ) { if ( x < 0 || y < 0 ) { return ; } const deltaX = x - Private . initialTouchPos . x ; const deltaY = y - Private . initialTouchPos . y ; Private . touchEvent . pressed = false ; Private . touchEvent . swipe = Math . max ( Math . abs ( deltaX ) , Math . abs ( deltaY ) ) > Private . swipeThreshold ; Private . touchEvent . x = x ; Private . touchEvent . y = y ; Private . touchEvent . swipeVelocity . set ( deltaX , deltaY ) ; Private . touchEvent . button = button ; Input . touchReleased . post ( Private . touchEvent ) ; } static onMouseWheel ( delta ) { Input . wheelMoved . post ( delta ) ; } }