Contrl.vue 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <template>
  2. <div>
  3. <div id="ctrl-left"></div>
  4. <div id="ctrl-right"></div>
  5. </div>
  6. </template>
  7. <script>
  8. import nipplejs from "nipplejs";
  9. const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
  10. export default {
  11. data() {
  12. return {
  13. contrlR: null,
  14. contrlL: null,
  15. timer: null,
  16. Option: {
  17. left: "20%",
  18. right: "20%",
  19. bottom: "30%",
  20. mode: "static",
  21. lcolor: "red",
  22. rcolor: "green",
  23. },
  24. contrlData: {
  25. v0: 128,
  26. v1: 128,
  27. v2: 128,
  28. v3: 128,
  29. },
  30. };
  31. },
  32. methods: {
  33. //初始化控制器
  34. initContrl() {
  35. this.contrlL = nipplejs.create({
  36. zone: document.getElementById("ctrl-left"),
  37. mode: this.Option.mode,
  38. position: {
  39. left: this.Option.left,
  40. bottom: this.Option.bottom,
  41. },
  42. color: this.Option.lcolor,
  43. });
  44. this.contrlR = nipplejs.create({
  45. zone: document.getElementById("ctrl-right"),
  46. mode: this.Option.mode,
  47. position: {
  48. right: this.Option.right,
  49. bottom: this.Option.bottom,
  50. },
  51. color: this.Option.rcolor,
  52. });
  53. this.contrlL.on("move", this.contrlLeft);
  54. this.contrlR.on("move", this.contrlRight);
  55. this.contrlL.on("end", this.contrlLeft);
  56. this.contrlR.on("end", this.contrlRight);
  57. this.loop();
  58. },
  59. // 摇杆左
  60. contrlLeft(a, b) {
  61. const obj = b.vector || { x: 0, y: 0 };
  62. this.contrlData.v2 = this.rotailContrl(obj.x);
  63. this.contrlData.v3 = this.rotailContrl(obj.y);
  64. },
  65. // 摇杆右
  66. contrlRight(a, b) {
  67. const obj = b.vector || { x: 0, y: 0 };
  68. this.contrlData.v0 = this.rotailContrl(obj.x);
  69. this.contrlData.v1 = this.rotailContrl(obj.y);
  70. },
  71. // 转换比例
  72. rotailContrl(v) {
  73. return Math.floor(Math.abs(v * 128 - 128));
  74. },
  75. // 发送回调
  76. async loop() {
  77. await sleep(50);
  78. this.$emit("callBack", this.contrlData);
  79. this.timer = requestAnimationFrame(this.loop);
  80. },
  81. // 清楚控制器
  82. clearContrl() {
  83. if (this.timer) cancelAnimationFrame(this.timer);
  84. if (this.contrlL) this.contrlL.destroy();
  85. if (this.contrlR) this.contrlR.destroy();
  86. },
  87. },
  88. destroyed() {
  89. this.clearContrl();
  90. },
  91. };
  92. </script>