virtualJoystick.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import { Nullable } from "../types";
  2. import { Vector3, Vector2 } from "../Maths/math.vector";
  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. VirtualJoystick.Canvas.style.touchAction = "none"; // fix https://forum.babylonjs.com/t/virtualjoystick-needs-to-set-style-touch-action-none-explicitly/9562
  114. // Support for jQuery PEP polyfill
  115. VirtualJoystick.Canvas.setAttribute("touch-action", "none");
  116. let context = VirtualJoystick.Canvas.getContext('2d');
  117. if (!context) {
  118. throw new Error("Unable to create canvas for virtual joystick");
  119. }
  120. VirtualJoystick.vjCanvasContext = context;
  121. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  122. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  123. document.body.appendChild(VirtualJoystick.Canvas);
  124. }
  125. VirtualJoystick.halfWidth = VirtualJoystick.Canvas.width / 2;
  126. this.pressed = false;
  127. // default joystick color
  128. this._joystickColor = "cyan";
  129. this._joystickPointerID = -1;
  130. // current joystick position
  131. this._joystickPointerPos = new Vector2(0, 0);
  132. this._joystickPreviousPointerPos = new Vector2(0, 0);
  133. // origin joystick position
  134. this._joystickPointerStartPos = new Vector2(0, 0);
  135. this._deltaJoystickVector = new Vector2(0, 0);
  136. this._onPointerDownHandlerRef = (evt) => {
  137. this._onPointerDown(evt);
  138. };
  139. this._onPointerMoveHandlerRef = (evt) => {
  140. this._onPointerMove(evt);
  141. };
  142. this._onPointerUpHandlerRef = (evt) => {
  143. this._onPointerUp(evt);
  144. };
  145. VirtualJoystick.Canvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  146. VirtualJoystick.Canvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  147. VirtualJoystick.Canvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  148. VirtualJoystick.Canvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  149. VirtualJoystick.Canvas.addEventListener("contextmenu", (evt) => {
  150. evt.preventDefault(); // Disables system menu
  151. }, false);
  152. requestAnimationFrame(() => { this._drawVirtualJoystick(); });
  153. }
  154. /**
  155. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  156. * @param newJoystickSensibility defines the new sensibility
  157. */
  158. public setJoystickSensibility(newJoystickSensibility: number) {
  159. this._joystickSensibility = newJoystickSensibility;
  160. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  161. }
  162. private _onPointerDown(e: PointerEvent) {
  163. var positionOnScreenCondition: boolean;
  164. e.preventDefault();
  165. if (this._leftJoystick === true) {
  166. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  167. }
  168. else {
  169. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  170. }
  171. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  172. // First contact will be dedicated to the virtual joystick
  173. this._joystickPointerID = e.pointerId;
  174. this._joystickPointerStartPos.x = e.clientX;
  175. this._joystickPointerStartPos.y = e.clientY;
  176. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  177. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  178. this._deltaJoystickVector.x = 0;
  179. this._deltaJoystickVector.y = 0;
  180. this.pressed = true;
  181. this._touches.add(e.pointerId.toString(), e);
  182. }
  183. else {
  184. // You can only trigger the action buttons with a joystick declared
  185. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  186. this._action();
  187. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  188. }
  189. }
  190. }
  191. private _onPointerMove(e: PointerEvent) {
  192. // If the current pointer is the one associated to the joystick (first touch contact)
  193. if (this._joystickPointerID == e.pointerId) {
  194. this._joystickPointerPos.x = e.clientX;
  195. this._joystickPointerPos.y = e.clientY;
  196. this._deltaJoystickVector = this._joystickPointerPos.clone();
  197. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  198. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  199. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  200. switch (this._axisTargetedByLeftAndRight) {
  201. case JoystickAxis.X:
  202. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  203. break;
  204. case JoystickAxis.Y:
  205. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  206. break;
  207. case JoystickAxis.Z:
  208. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  209. break;
  210. }
  211. var directionUpDown = this.reverseUpDown ? 1 : -1;
  212. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  213. switch (this._axisTargetedByUpAndDown) {
  214. case JoystickAxis.X:
  215. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  216. break;
  217. case JoystickAxis.Y:
  218. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  219. break;
  220. case JoystickAxis.Z:
  221. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  222. break;
  223. }
  224. }
  225. else {
  226. let data = this._touches.get(e.pointerId.toString());
  227. if (data) {
  228. (data as any).x = e.clientX;
  229. (data as any).y = e.clientY;
  230. }
  231. }
  232. }
  233. private _onPointerUp(e: PointerEvent) {
  234. if (this._joystickPointerID == e.pointerId) {
  235. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  236. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  237. this._joystickPointerID = -1;
  238. this.pressed = false;
  239. }
  240. else {
  241. var touch = <{ x: number, y: number, prevX: number, prevY: number }>this._touches.get(e.pointerId.toString());
  242. if (touch) {
  243. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  244. }
  245. }
  246. this._deltaJoystickVector.x = 0;
  247. this._deltaJoystickVector.y = 0;
  248. this._touches.remove(e.pointerId.toString());
  249. }
  250. /**
  251. * Change the color of the virtual joystick
  252. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  253. */
  254. public setJoystickColor(newColor: string) {
  255. this._joystickColor = newColor;
  256. }
  257. /**
  258. * Defines a callback to call when the joystick is touched
  259. * @param action defines the callback
  260. */
  261. public setActionOnTouch(action: () => any) {
  262. this._action = action;
  263. }
  264. /**
  265. * Defines which axis you'd like to control for left & right
  266. * @param axis defines the axis to use
  267. */
  268. public setAxisForLeftRight(axis: JoystickAxis) {
  269. switch (axis) {
  270. case JoystickAxis.X:
  271. case JoystickAxis.Y:
  272. case JoystickAxis.Z:
  273. this._axisTargetedByLeftAndRight = axis;
  274. break;
  275. default:
  276. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  277. break;
  278. }
  279. }
  280. /**
  281. * Defines which axis you'd like to control for up & down
  282. * @param axis defines the axis to use
  283. */
  284. public setAxisForUpDown(axis: JoystickAxis) {
  285. switch (axis) {
  286. case JoystickAxis.X:
  287. case JoystickAxis.Y:
  288. case JoystickAxis.Z:
  289. this._axisTargetedByUpAndDown = axis;
  290. break;
  291. default:
  292. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  293. break;
  294. }
  295. }
  296. private _drawVirtualJoystick() {
  297. if (this.pressed) {
  298. this._touches.forEach((key, touch) => {
  299. if ((<PointerEvent>touch).pointerId === this._joystickPointerID) {
  300. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  301. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  302. VirtualJoystick.vjCanvasContext.beginPath();
  303. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  304. VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
  305. VirtualJoystick.vjCanvasContext.arc(this._joystickPointerStartPos.x, this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  306. VirtualJoystick.vjCanvasContext.stroke();
  307. VirtualJoystick.vjCanvasContext.closePath();
  308. VirtualJoystick.vjCanvasContext.beginPath();
  309. VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
  310. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  311. VirtualJoystick.vjCanvasContext.arc(this._joystickPointerStartPos.x, this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  312. VirtualJoystick.vjCanvasContext.stroke();
  313. VirtualJoystick.vjCanvasContext.closePath();
  314. VirtualJoystick.vjCanvasContext.beginPath();
  315. VirtualJoystick.vjCanvasContext.strokeStyle = this._joystickColor;
  316. VirtualJoystick.vjCanvasContext.arc(this._joystickPointerPos.x, this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  317. VirtualJoystick.vjCanvasContext.stroke();
  318. VirtualJoystick.vjCanvasContext.closePath();
  319. this._joystickPreviousPointerPos = this._joystickPointerPos.clone();
  320. }
  321. else {
  322. VirtualJoystick.vjCanvasContext.clearRect((<any>touch).prevX - 44, (<any>touch).prevY - 44, 88, 88);
  323. VirtualJoystick.vjCanvasContext.beginPath();
  324. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  325. VirtualJoystick.vjCanvasContext.beginPath();
  326. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  327. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  328. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  329. VirtualJoystick.vjCanvasContext.stroke();
  330. VirtualJoystick.vjCanvasContext.closePath();
  331. (<any>touch).prevX = touch.x;
  332. (<any>touch).prevY = touch.y;
  333. }
  334. });
  335. }
  336. requestAnimationFrame(() => { this._drawVirtualJoystick(); });
  337. }
  338. /**
  339. * Release internal HTML canvas
  340. */
  341. public releaseCanvas() {
  342. if (VirtualJoystick.Canvas) {
  343. VirtualJoystick.Canvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  344. VirtualJoystick.Canvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  345. VirtualJoystick.Canvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  346. VirtualJoystick.Canvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  347. window.removeEventListener("resize", this._onResize);
  348. document.body.removeChild(VirtualJoystick.Canvas);
  349. VirtualJoystick.Canvas = null;
  350. }
  351. }
  352. }