babylon.virtualJoystick.ts 17 KB

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