JoyStick.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. export default class JoyStick {
  2. constructor(e) {
  3. this._zone = document.createElement("div")
  4. this._joystick = null
  5. this._room = e
  6. }
  7. init(e) {
  8. const { interval=33, triggerDistance=25, style={left:0, bottom:0} } = e
  9. const moveFunc = (u,c)=>{
  10. this._room.actionsHandler.joystick({
  11. degree: Math.floor(u),
  12. level: Math.floor(c / 5)
  13. })
  14. }
  15. const a = this._zone;
  16. document.body.appendChild(a),
  17. a.style.position = "absolute",
  18. a.style.width = style.width || "200px",
  19. a.style.height = style.height || "200px",
  20. a.style.left = String(style.left || 0),
  21. a.style.bottom = String(style.bottom || 0),
  22. a.style.zIndex = "999",
  23. a.style.userSelect = "none",
  24. a.style.webkitUserSelect = "none",
  25. this._joystick = nipplejs.create({
  26. zone: a,
  27. mode: "static",
  28. position: {
  29. left: "50%",
  30. top: "50%"
  31. },
  32. color: "white"
  33. });
  34. let s, l;
  35. this._joystick.on("move", (u,c)=>{
  36. s = c
  37. })
  38. this._joystick.on("start", ()=>{
  39. l = window.setInterval(()=>{
  40. s && s.distance > triggerDistance && moveFunc && moveFunc(s.angle.degree, s.distance)
  41. }
  42. , interval)
  43. })
  44. this._joystick.on("end", ()=>{
  45. l && window.clearInterval(l),
  46. l = void 0
  47. })
  48. return this._joystick
  49. }
  50. show() {
  51. if (!this._joystick)
  52. throw new Error("joystick is not created");
  53. this._zone.style.display = "block"
  54. }
  55. hide() {
  56. if (!this._joystick)
  57. throw new Error("joystick is not created");
  58. this._zone.style.display = "none"
  59. }
  60. }