virtualJoystick.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import { Nullable } from "../types";
  2. import { Vector3, Vector2 } from "../Maths/math";
  3. import { StringDictionary } from "./stringDictionary";
  4. // Mainly based on these 2 articles :
  5. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  6. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  7. /**
  8. * Defines the potential axis of a Joystick
  9. */
  10. export enum JoystickAxis {
  11. /** X axis */
  12. X,
  13. /** Y axis */
  14. Y,
  15. /** Z axis */
  16. Z
  17. }
  18. /**
  19. * Class used to define virtual joystick (used in touch mode)
  20. */
  21. export class VirtualJoystick {
  22. /**
  23. * Gets or sets a boolean indicating that left and right values must be inverted
  24. */
  25. public reverseLeftRight: boolean;
  26. /**
  27. * Gets or sets a boolean indicating that up and down values must be inverted
  28. */
  29. public reverseUpDown: boolean;
  30. /**
  31. * Gets the offset value for the position (ie. the change of the position value)
  32. */
  33. public deltaPosition: Vector3;
  34. /**
  35. * Gets a boolean indicating if the virtual joystick was pressed
  36. */
  37. public pressed: boolean;
  38. /**
  39. * Canvas the virtual joystick will render onto, default z-index of this is 5
  40. */
  41. public static Canvas: Nullable<HTMLCanvasElement>;
  42. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  43. private static _globalJoystickIndex: number = 0;
  44. private static vjCanvasContext: CanvasRenderingContext2D;
  45. private static vjCanvasWidth: number;
  46. private static vjCanvasHeight: number;
  47. private static halfWidth: number;
  48. private _action: () => any;
  49. private _axisTargetedByLeftAndRight: JoystickAxis;
  50. private _axisTargetedByUpAndDown: JoystickAxis;
  51. private _joystickSensibility: number;
  52. private _inversedSensibility: number;
  53. private _joystickPointerID: number;
  54. private _joystickColor: string;
  55. private _joystickPointerPos: Vector2;
  56. private _joystickPreviousPointerPos: Vector2;
  57. private _joystickPointerStartPos: Vector2;
  58. private _deltaJoystickVector: Vector2;
  59. private _leftJoystick: boolean;
  60. private _touches: StringDictionary<{ x: number, y: number, prevX: number, prevY: number } | PointerEvent>;
  61. private _onPointerDownHandlerRef: (e: PointerEvent) => any;
  62. private _onPointerMoveHandlerRef: (e: PointerEvent) => any;
  63. private _onPointerUpHandlerRef: (e: PointerEvent) => any;
  64. private _onResize: (e: any) => any;
  65. /**
  66. * Creates a new virtual joystick
  67. * @param leftJoystick defines that the joystick is for left hand (false by default)
  68. */
  69. constructor(leftJoystick?: boolean) {
  70. if (leftJoystick) {
  71. this._leftJoystick = true;
  72. }
  73. else {
  74. this._leftJoystick = false;
  75. }
  76. VirtualJoystick._globalJoystickIndex++;
  77. // By default left & right arrow keys are moving the X
  78. // and up & down keys are moving the Y
  79. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81. this.reverseLeftRight = false;
  82. this.reverseUpDown = false;
  83. // collections of pointers
  84. this._touches = new StringDictionary<{ x: number, y: number, prevX: number, prevY: number } | PointerEvent>();
  85. this.deltaPosition = Vector3.Zero();
  86. this._joystickSensibility = 25;
  87. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88. this._onResize = (evt) => {
  89. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  90. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91. if (VirtualJoystick.Canvas) {
  92. VirtualJoystick.Canvas.width = VirtualJoystick.vjCanvasWidth;
  93. VirtualJoystick.Canvas.height = VirtualJoystick.vjCanvasHeight;
  94. }
  95. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  96. };
  97. // injecting a canvas element on top of the canvas 3D game
  98. if (!VirtualJoystick.Canvas) {
  99. window.addEventListener("resize", this._onResize, false);
  100. VirtualJoystick.Canvas = document.createElement("canvas");
  101. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  103. VirtualJoystick.Canvas.width = window.innerWidth;
  104. VirtualJoystick.Canvas.height = window.innerHeight;
  105. VirtualJoystick.Canvas.style.width = "100%";
  106. VirtualJoystick.Canvas.style.height = "100%";
  107. VirtualJoystick.Canvas.style.position = "absolute";
  108. VirtualJoystick.Canvas.style.backgroundColor = "transparent";
  109. VirtualJoystick.Canvas.style.top = "0px";
  110. VirtualJoystick.Canvas.style.left = "0px";
  111. VirtualJoystick.Canvas.style.zIndex = "5";
  112. VirtualJoystick.Canvas.style.msTouchAction = "none";
  113. // Support for jQuery PEP polyfill
  114. VirtualJoystick.Canvas.setAttribute("touch-action", "none");
  115. let context = VirtualJoystick.Canvas.getContext('2d');
  116. if (!context) {
  117. throw new Error("Unable to create canvas for virtual joystick");
  118. }
  119. VirtualJoystick.vjCanvasContext = context;
  120. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  121. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  122. document.body.appendChild(VirtualJoystick.Canvas);
  123. }
  124. VirtualJoystick.halfWidth = VirtualJoystick.Canvas.width / 2;
  125. this.pressed = false;
  126. // default joystick color
  127. this._joystickColor = "cyan";
  128. this._joystickPointerID = -1;
  129. // current joystick position
  130. this._joystickPointerPos = new Vector2(0, 0);
  131. this._joystickPreviousPointerPos = new Vector2(0, 0);
  132. // origin joystick position
  133. this._joystickPointerStartPos = new Vector2(0, 0);
  134. this._deltaJoystickVector = new Vector2(0, 0);
  135. this._onPointerDownHandlerRef = (evt) => {
  136. this._onPointerDown(evt);
  137. };
  138. this._onPointerMoveHandlerRef = (evt) => {
  139. this._onPointerMove(evt);
  140. };
  141. this._onPointerUpHandlerRef = (evt) => {
  142. this._onPointerUp(evt);
  143. };
  144. VirtualJoystick.Canvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  145. VirtualJoystick.Canvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  146. VirtualJoystick.Canvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  147. VirtualJoystick.Canvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  148. VirtualJoystick.Canvas.addEventListener("contextmenu", (evt) => {
  149. evt.preventDefault(); // Disables system menu
  150. }, false);
  151. requestAnimationFrame(() => { this._drawVirtualJoystick(); });
  152. }
  153. /**
  154. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  155. * @param newJoystickSensibility defines the new sensibility
  156. */
  157. public setJoystickSensibility(newJoystickSensibility: number) {
  158. this._joystickSensibility = newJoystickSensibility;
  159. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  160. }
  161. private _onPointerDown(e: PointerEvent) {
  162. var positionOnScreenCondition: boolean;
  163. e.preventDefault();
  164. if (this._leftJoystick === true) {
  165. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  166. }
  167. else {
  168. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  169. }
  170. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  171. // First contact will be dedicated to the virtual joystick
  172. this._joystickPointerID = e.pointerId;
  173. this._joystickPointerStartPos.x = e.clientX;
  174. this._joystickPointerStartPos.y = e.clientY;
  175. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  176. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  177. this._deltaJoystickVector.x = 0;
  178. this._deltaJoystickVector.y = 0;
  179. this.pressed = true;
  180. this._touches.add(e.pointerId.toString(), e);
  181. }
  182. else {
  183. // You can only trigger the action buttons with a joystick declared
  184. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  185. this._action();
  186. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  187. }
  188. }
  189. }
  190. private _onPointerMove(e: PointerEvent) {
  191. // If the current pointer is the one associated to the joystick (first touch contact)
  192. if (this._joystickPointerID == e.pointerId) {
  193. this._joystickPointerPos.x = e.clientX;
  194. this._joystickPointerPos.y = e.clientY;
  195. this._deltaJoystickVector = this._joystickPointerPos.clone();
  196. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  197. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  198. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  199. switch (this._axisTargetedByLeftAndRight) {
  200. case JoystickAxis.X:
  201. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  202. break;
  203. case JoystickAxis.Y:
  204. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  205. break;
  206. case JoystickAxis.Z:
  207. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  208. break;
  209. }
  210. var directionUpDown = this.reverseUpDown ? 1 : -1;
  211. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  212. switch (this._axisTargetedByUpAndDown) {
  213. case JoystickAxis.X:
  214. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  215. break;
  216. case JoystickAxis.Y:
  217. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  218. break;
  219. case JoystickAxis.Z:
  220. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  221. break;
  222. }
  223. }
  224. else {
  225. let data = this._touches.get(e.pointerId.toString());
  226. if (data) {
  227. (data as any).x = e.clientX;
  228. (data as any).y = e.clientY;
  229. }
  230. }
  231. }
  232. private _onPointerUp(e: PointerEvent) {
  233. if (this._joystickPointerID == e.pointerId) {
  234. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  235. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  236. this._joystickPointerID = -1;
  237. this.pressed = false;
  238. }
  239. else {
  240. var touch = <{ x: number, y: number, prevX: number, prevY: number }>this._touches.get(e.pointerId.toString());
  241. if (touch) {
  242. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  243. }
  244. }
  245. this._deltaJoystickVector.x = 0;
  246. this._deltaJoystickVector.y = 0;
  247. this._touches.remove(e.pointerId.toString());
  248. }
  249. /**
  250. * Change the color of the virtual joystick
  251. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  252. */
  253. public setJoystickColor(newColor: string) {
  254. this._joystickColor = newColor;
  255. }
  256. /**
  257. * Defines a callback to call when the joystick is touched
  258. * @param action defines the callback
  259. */
  260. public setActionOnTouch(action: () => any) {
  261. this._action = action;
  262. }
  263. /**
  264. * Defines which axis you'd like to control for left & right
  265. * @param axis defines the axis to use
  266. */
  267. public setAxisForLeftRight(axis: JoystickAxis) {
  268. switch (axis) {
  269. case JoystickAxis.X:
  270. case JoystickAxis.Y:
  271. case JoystickAxis.Z:
  272. this._axisTargetedByLeftAndRight = axis;
  273. break;
  274. default:
  275. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  276. break;
  277. }
  278. }
  279. /**
  280. * Defines which axis you'd like to control for up & down
  281. * @param axis defines the axis to use
  282. */
  283. public setAxisForUpDown(axis: JoystickAxis) {
  284. switch (axis) {
  285. case JoystickAxis.X:
  286. case JoystickAxis.Y:
  287. case JoystickAxis.Z:
  288. this._axisTargetedByUpAndDown = axis;
  289. break;
  290. default:
  291. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  292. break;
  293. }
  294. }
  295. private _drawVirtualJoystick() {
  296. if (this.pressed) {
  297. this._touches.forEach((key, touch) => {
  298. if ((<PointerEvent>touch).pointerId === this._joystickPointerID) {
  299. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  300. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  301. VirtualJoystick.vjCanvasContext.beginPath();
  302. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  303. VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
  304. VirtualJoystick.vjCanvasContext.arc(this._joystickPointerStartPos.x, this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  305. VirtualJoystick.vjCanvasContext.stroke();
  306. VirtualJoystick.vjCanvasContext.closePath();
  307. VirtualJoystick.vjCanvasContext.beginPath();
  308. VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
  309. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  310. VirtualJoystick.vjCanvasContext.arc(this._joystickPointerStartPos.x, this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  311. VirtualJoystick.vjCanvasContext.stroke();
  312. VirtualJoystick.vjCanvasContext.closePath();
  313. VirtualJoystick.vjCanvasContext.beginPath();
  314. VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
  315. VirtualJoystick.vjCanvasContext.arc(this._joystickPointerPos.x, this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  316. VirtualJoystick.vjCanvasContext.stroke();
  317. VirtualJoystick.vjCanvasContext.closePath();
  318. this._joystickPreviousPointerPos = this._joystickPointerPos.clone();
  319. }
  320. else {
  321. VirtualJoystick.vjCanvasContext.clearRect((<any>touch).prevX - 44, (<any>touch).prevY - 44, 88, 88);
  322. VirtualJoystick.vjCanvasContext.beginPath();
  323. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  324. VirtualJoystick.vjCanvasContext.beginPath();
  325. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  326. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  327. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  328. VirtualJoystick.vjCanvasContext.stroke();
  329. VirtualJoystick.vjCanvasContext.closePath();
  330. (<any>touch).prevX = touch.x;
  331. (<any>touch).prevY = touch.y;
  332. }
  333. });
  334. }
  335. requestAnimationFrame(() => { this._drawVirtualJoystick(); });
  336. }
  337. /**
  338. * Release internal HTML canvas
  339. */
  340. public releaseCanvas() {
  341. if (VirtualJoystick.Canvas) {
  342. VirtualJoystick.Canvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  343. VirtualJoystick.Canvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  344. VirtualJoystick.Canvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  345. VirtualJoystick.Canvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  346. window.removeEventListener("resize", this._onResize);
  347. document.body.removeChild(VirtualJoystick.Canvas);
  348. VirtualJoystick.Canvas = null;
  349. }
  350. }
  351. }