Advertisement
jargon

Linedancer (LD4) :: "UI/Gamepad Class.js"

Dec 29th, 2024 (edited)
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Linedancer (LD4) :: "UI/Gamepad Class.js"
  2.  
  3. class GamepadManager {
  4.    
  5.     constructor() {
  6.         this.gamepads = [];
  7.     }
  8.  
  9.     addGamepad(canvasId) {
  10.         const gamepad = new Gamepad(canvasId);
  11.         if (gamepad.isValid()) {
  12.             this.gamepads.push(gamepad);
  13.         }
  14.     }
  15.  
  16.     drawAllGamepads() {
  17.         this.gamepads.forEach((gamepad) => gamepad.drawGamepad());
  18.     }
  19. }
  20.  
  21. class Gamepad {
  22.    
  23.     constructor(canvasId) {
  24.        
  25.         this.config = /* {{ raw#/LD4/Linedancer/scripts/json/UI/Gamepad Config.json }} */;
  26.        
  27.         this.zones = {};
  28.        
  29.         this.canvas = document.getElementById(canvasId);
  30.         if (!this.canvas) {
  31.             console.error(`Canvas with id '${canvasId}' not found.`);
  32.             this.valid = false;
  33.             return;
  34.         }
  35.  
  36.         this.context = this.canvas.getContext('2d');
  37.         this.resizeCanvas();
  38.  
  39.         this.valid = true;
  40.         this.gamepadState = {
  41.             buttons: {},
  42.             joysticks: [],
  43.         };
  44.  
  45.         this.activeTouches = {};
  46.  
  47.         this.initializeFromConfig();
  48.         this.drawGamepad();
  49.  
  50.         this.addEventListeners();
  51.         window.addEventListener('resize', () => this.resizeCanvas());
  52.     }
  53.  
  54.     isValid() {
  55.         return this.valid;
  56.     }
  57.  
  58.     initializeFromConfig() {
  59.        
  60.         console.log("Loaded Config:", this.config);
  61.         if (Array.isArray(this.config.buttons)) {
  62.             this.config.buttons.forEach((button) => {
  63.                 this.gamepadState.buttons[button.name] = false;
  64.                 this.zones[button.name] = {
  65.                     x: button.x,
  66.                     y: button.y,
  67.                     radius: button.radius,
  68.                 };
  69.             });
  70.         }
  71.    
  72.         if (Array.isArray(this.config.joysticks)) {
  73.             this.config.joysticks.forEach((joystick, index) => {
  74.                 this.gamepadState.joysticks[index] = { x: 0, y: 0 };
  75.                 this.zones[`joystick${index}`] = joystick;
  76.             });
  77.         }
  78.         console.log("Initialized Zones:", this.zones);
  79.     }
  80.    
  81.     resizeCanvas() {
  82.         this.canvas.width = window.innerWidth;
  83.         this.canvas.height = window.innerHeight;
  84.         this.drawGamepad();
  85.     }
  86.  
  87.     drawGamepad() {
  88.        
  89.         this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  90.    
  91.         // Draw buttons
  92.         for (const button in this.zones) {
  93.             const zone = this.zones[button];
  94.             if (!zone) continue; // Skip if zone is undefined
  95.             if (!button.startsWith('joystick')) {
  96.                 this.context.beginPath();
  97.                 this.context.arc(zone.x, zone.y, zone.radius, 0, Math.PI * 2);
  98.                 this.context.fillStyle = this.gamepadState.buttons[button]
  99.                     ? 'rgba(255, 0, 0, 0.5)'
  100.                     : 'rgba(0, 255, 0, 0.5)';
  101.                 this.context.fill();
  102.                 this.context.strokeStyle = 'white';
  103.                 this.context.lineWidth = 2;
  104.                 this.context.stroke();
  105.                 this.context.fillStyle = 'white';
  106.                 this.context.font = '16px Arial';
  107.                 this.context.textAlign = 'center';
  108.                 this.context.fillText(button, zone.x, zone.y + 5);
  109.             }
  110.         }
  111.    
  112.         // Draw joysticks
  113.         if (Array.isArray(this.config.joysticks)) {
  114.             this.config.joysticks.forEach((joystick, index) => {
  115.                 const zoneKey = `joystick${index}`;
  116.                 const zone = this.zones[zoneKey];
  117.                 if (!zone) return; // Skip if zone is undefined
  118.    
  119.                 this.context.beginPath();
  120.                 this.context.arc(zone.x, zone.y, zone.radius, 0, Math.PI * 2);
  121.                 this.context.strokeStyle = 'white';
  122.                 this.context.lineWidth = 2;
  123.                 this.context.stroke();
  124.    
  125.                 this.context.beginPath();
  126.                 const joyHandleX = zone.x + this.gamepadState.joysticks[index].x * 50;
  127.                 const joyHandleY = zone.y + this.gamepadState.joysticks[index].y * 50;
  128.                 this.context.arc(joyHandleX, joyHandleY, 20, 0, Math.PI * 2);
  129.                 this.context.fillStyle = 'white';
  130.                 this.context.fill();
  131.             });
  132.         }
  133.     }
  134.    
  135.     loadConfig() {    
  136.         try {
  137.             this.config = /* {{ raw#/LD4/Linedancer/scripts/json/UI/Gamepad Config.json }} */;
  138.             if (!this.config || typeof this.config !== 'object') {
  139.                 throw new Error('Configuration file is empty or invalid.');
  140.             }
  141.         } catch (error) {
  142.             console.error("Failed to load gamepad configuration:", error);
  143.             this.config = { buttons: [], joysticks: [] }; // Provide default structure
  144.         }
  145.     }
  146.    
  147.         addEventListeners() {
  148.         this.canvas.addEventListener('touchstart', (event) => this.onTouchStart(event));
  149.         this.canvas.addEventListener('touchmove', (event) => this.onTouchMove(event));
  150.         this.canvas.addEventListener('touchend', (event) => this.onTouchEnd(event));
  151.     }
  152.  
  153.     removeEventListeners() {
  154.         this.canvas.removeEventListener('touchstart', this.onTouchStart);
  155.         this.canvas.removeEventListener('touchmove', this.onTouchMove);
  156.         this.canvas.removeEventListener('touchend', this.onTouchEnd);
  157.         window.removeEventListener('resize', this.resizeCanvas);
  158.     }
  159.  
  160.     updateJoystick
  161.     (
  162.         joystick,
  163.         x,
  164.         y
  165.     )
  166.     {
  167.         const dx = x - this.zones[joystick].x;
  168.         const dy = y - this.zones[joystick].y;
  169.         const maxDistance = this.zones[joystick].radius;
  170.         const distance = Math.min(Math.sqrt(dx * dx + dy * dy), maxDistance);
  171.  
  172.         this.gamepadState[joystick].x = dx / maxDistance;
  173.         this.gamepadState[joystick].y = dy / maxDistance;
  174.     }
  175.  
  176.     onTouchStart (event)
  177.     {
  178.         for (const touch of event.changedTouches) {
  179.             this.activeTouches[touch.identifier] = { x: touch.clientX, y: touch.clientY };
  180.  
  181.             // Check zones
  182.             for (const button in this.zones) {
  183.                 const zone = this.zones[button];
  184.                 const dx = touch.clientX - zone.x;
  185.                 const dy = touch.clientY - zone.y;
  186.                 const distance = Math.sqrt(dx * dx + dy * dy);
  187.  
  188.                 if (distance < zone.radius) {
  189.                     if (button === 'joystick1' || button === 'joystick2') {
  190.                         this.updateJoystick(button, touch.clientX, touch.clientY);
  191.                     } else {
  192.                         this.gamepadState.buttons[button] = true;
  193.                     }
  194.                 }
  195.             }
  196.         }
  197.         this.drawGamepad();
  198.     }
  199.  
  200.     onTouchMove (event)
  201.     {
  202.         for (const touch of event.changedTouches) {
  203.             if (this.activeTouches[touch.identifier]) {
  204.                 this.activeTouches[touch.identifier] = { x: touch.clientX, y: touch.clientY };
  205.  
  206.                 // Update joysticks
  207.                 for (const joystick of ['joystick1', 'joystick2']) {
  208.                     if (this.zones[joystick]) {
  209.                         const dx = touch.clientX - this.zones[joystick].x;
  210.                         const dy = touch.clientY - this.zones[joystick].y;
  211.                         const distance = Math.sqrt(dx * dx + dy * dy);
  212.                         if (distance < this.zones[joystick].radius) {
  213.                             this.updateJoystick(joystick, touch.clientX, touch.clientY);
  214.                         }
  215.                     }
  216.                 }
  217.             }
  218.         }
  219.         this.drawGamepad();
  220.     }
  221.  
  222.     onTouchEnd (event)
  223.     {
  224.         for (const touch of event.changedTouches) {
  225.             delete this.activeTouches[touch.identifier];
  226.  
  227.             // Reset buttons
  228.             for (const button in this.zones) {
  229.                 if (button !== 'joystick1' && button !== 'joystick2') {
  230.                     this.gamepadState.buttons[button] = false;
  231.                 }
  232.             }
  233.  
  234.             // Reset joysticks
  235.             this.gamepadState.joystick1 = { x: 0, y: 0 };
  236.             this.gamepadState.joystick2 = { x: 0, y: 0 };
  237.         }
  238.         this.drawGamepad();
  239.     }
  240. }
  241.  
  242. // Initialize the GamepadManager and load the first gamepad
  243. document.addEventListener('DOMContentLoaded', () => {
  244.     const canvasId = 'gamepadCanvas';
  245.  
  246.     // Dynamically create the canvas element if it doesn't exist
  247.     let canvas = document.getElementById(canvasId);
  248.     if (!canvas) {
  249.         console.log(`Canvas with ID '${canvasId}' not found. Creating one dynamically.`);
  250.         canvas = document.createElement('canvas');
  251.         canvas.id = canvasId;
  252.         canvas.width = 800; // Default width
  253.         canvas.height = 600; // Default height
  254.         document.body.appendChild(canvas); // Append it to the body or a container element
  255.     }
  256.  
  257.     const gamepadManager = new GamepadManager();
  258.  
  259.     console.log('Attempting to add gamepad...');
  260.     gamepadManager.addGamepad(canvasId);
  261.  
  262.     if (gamepadManager.gamepads.length > 0) {
  263.         console.log('Gamepad initialized successfully.');
  264.         gamepadManager.drawAllGamepads();
  265.     } else {
  266.         console.error('Gamepad initialization failed. Verify canvasId and configuration.');
  267.     }
  268. });
  269.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement