Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Linedancer (LD4) :: "UI/Gamepad Class.js"
- class GamepadManager {
- constructor() {
- this.gamepads = [];
- }
- addGamepad(canvasId) {
- const gamepad = new Gamepad(canvasId);
- if (gamepad.isValid()) {
- this.gamepads.push(gamepad);
- }
- }
- drawAllGamepads() {
- this.gamepads.forEach((gamepad) => gamepad.drawGamepad());
- }
- }
- class Gamepad {
- constructor(canvasId) {
- this.config = /* {{ raw#/LD4/Linedancer/scripts/json/UI/Gamepad Config.json }} */;
- this.zones = {};
- this.canvas = document.getElementById(canvasId);
- if (!this.canvas) {
- console.error(`Canvas with id '${canvasId}' not found.`);
- this.valid = false;
- return;
- }
- this.context = this.canvas.getContext('2d');
- this.resizeCanvas();
- this.valid = true;
- this.gamepadState = {
- buttons: {},
- joysticks: [],
- };
- this.activeTouches = {};
- this.initializeFromConfig();
- this.drawGamepad();
- this.addEventListeners();
- window.addEventListener('resize', () => this.resizeCanvas());
- }
- isValid() {
- return this.valid;
- }
- initializeFromConfig() {
- console.log("Loaded Config:", this.config);
- if (Array.isArray(this.config.buttons)) {
- this.config.buttons.forEach((button) => {
- this.gamepadState.buttons[button.name] = false;
- this.zones[button.name] = {
- x: button.x,
- y: button.y,
- radius: button.radius,
- };
- });
- }
- if (Array.isArray(this.config.joysticks)) {
- this.config.joysticks.forEach((joystick, index) => {
- this.gamepadState.joysticks[index] = { x: 0, y: 0 };
- this.zones[`joystick${index}`] = joystick;
- });
- }
- console.log("Initialized Zones:", this.zones);
- }
- resizeCanvas() {
- this.canvas.width = window.innerWidth;
- this.canvas.height = window.innerHeight;
- this.drawGamepad();
- }
- drawGamepad() {
- this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
- // Draw buttons
- for (const button in this.zones) {
- const zone = this.zones[button];
- if (!zone) continue; // Skip if zone is undefined
- if (!button.startsWith('joystick')) {
- this.context.beginPath();
- this.context.arc(zone.x, zone.y, zone.radius, 0, Math.PI * 2);
- this.context.fillStyle = this.gamepadState.buttons[button]
- ? 'rgba(255, 0, 0, 0.5)'
- : 'rgba(0, 255, 0, 0.5)';
- this.context.fill();
- this.context.strokeStyle = 'white';
- this.context.lineWidth = 2;
- this.context.stroke();
- this.context.fillStyle = 'white';
- this.context.font = '16px Arial';
- this.context.textAlign = 'center';
- this.context.fillText(button, zone.x, zone.y + 5);
- }
- }
- // Draw joysticks
- if (Array.isArray(this.config.joysticks)) {
- this.config.joysticks.forEach((joystick, index) => {
- const zoneKey = `joystick${index}`;
- const zone = this.zones[zoneKey];
- if (!zone) return; // Skip if zone is undefined
- this.context.beginPath();
- this.context.arc(zone.x, zone.y, zone.radius, 0, Math.PI * 2);
- this.context.strokeStyle = 'white';
- this.context.lineWidth = 2;
- this.context.stroke();
- this.context.beginPath();
- const joyHandleX = zone.x + this.gamepadState.joysticks[index].x * 50;
- const joyHandleY = zone.y + this.gamepadState.joysticks[index].y * 50;
- this.context.arc(joyHandleX, joyHandleY, 20, 0, Math.PI * 2);
- this.context.fillStyle = 'white';
- this.context.fill();
- });
- }
- }
- loadConfig() {
- try {
- this.config = /* {{ raw#/LD4/Linedancer/scripts/json/UI/Gamepad Config.json }} */;
- if (!this.config || typeof this.config !== 'object') {
- throw new Error('Configuration file is empty or invalid.');
- }
- } catch (error) {
- console.error("Failed to load gamepad configuration:", error);
- this.config = { buttons: [], joysticks: [] }; // Provide default structure
- }
- }
- addEventListeners() {
- this.canvas.addEventListener('touchstart', (event) => this.onTouchStart(event));
- this.canvas.addEventListener('touchmove', (event) => this.onTouchMove(event));
- this.canvas.addEventListener('touchend', (event) => this.onTouchEnd(event));
- }
- removeEventListeners() {
- this.canvas.removeEventListener('touchstart', this.onTouchStart);
- this.canvas.removeEventListener('touchmove', this.onTouchMove);
- this.canvas.removeEventListener('touchend', this.onTouchEnd);
- window.removeEventListener('resize', this.resizeCanvas);
- }
- updateJoystick
- (
- joystick,
- x,
- y
- )
- {
- const dx = x - this.zones[joystick].x;
- const dy = y - this.zones[joystick].y;
- const maxDistance = this.zones[joystick].radius;
- const distance = Math.min(Math.sqrt(dx * dx + dy * dy), maxDistance);
- this.gamepadState[joystick].x = dx / maxDistance;
- this.gamepadState[joystick].y = dy / maxDistance;
- }
- onTouchStart (event)
- {
- for (const touch of event.changedTouches) {
- this.activeTouches[touch.identifier] = { x: touch.clientX, y: touch.clientY };
- // Check zones
- for (const button in this.zones) {
- const zone = this.zones[button];
- const dx = touch.clientX - zone.x;
- const dy = touch.clientY - zone.y;
- const distance = Math.sqrt(dx * dx + dy * dy);
- if (distance < zone.radius) {
- if (button === 'joystick1' || button === 'joystick2') {
- this.updateJoystick(button, touch.clientX, touch.clientY);
- } else {
- this.gamepadState.buttons[button] = true;
- }
- }
- }
- }
- this.drawGamepad();
- }
- onTouchMove (event)
- {
- for (const touch of event.changedTouches) {
- if (this.activeTouches[touch.identifier]) {
- this.activeTouches[touch.identifier] = { x: touch.clientX, y: touch.clientY };
- // Update joysticks
- for (const joystick of ['joystick1', 'joystick2']) {
- if (this.zones[joystick]) {
- const dx = touch.clientX - this.zones[joystick].x;
- const dy = touch.clientY - this.zones[joystick].y;
- const distance = Math.sqrt(dx * dx + dy * dy);
- if (distance < this.zones[joystick].radius) {
- this.updateJoystick(joystick, touch.clientX, touch.clientY);
- }
- }
- }
- }
- }
- this.drawGamepad();
- }
- onTouchEnd (event)
- {
- for (const touch of event.changedTouches) {
- delete this.activeTouches[touch.identifier];
- // Reset buttons
- for (const button in this.zones) {
- if (button !== 'joystick1' && button !== 'joystick2') {
- this.gamepadState.buttons[button] = false;
- }
- }
- // Reset joysticks
- this.gamepadState.joystick1 = { x: 0, y: 0 };
- this.gamepadState.joystick2 = { x: 0, y: 0 };
- }
- this.drawGamepad();
- }
- }
- // Initialize the GamepadManager and load the first gamepad
- document.addEventListener('DOMContentLoaded', () => {
- const canvasId = 'gamepadCanvas';
- // Dynamically create the canvas element if it doesn't exist
- let canvas = document.getElementById(canvasId);
- if (!canvas) {
- console.log(`Canvas with ID '${canvasId}' not found. Creating one dynamically.`);
- canvas = document.createElement('canvas');
- canvas.id = canvasId;
- canvas.width = 800; // Default width
- canvas.height = 600; // Default height
- document.body.appendChild(canvas); // Append it to the body or a container element
- }
- const gamepadManager = new GamepadManager();
- console.log('Attempting to add gamepad...');
- gamepadManager.addGamepad(canvasId);
- if (gamepadManager.gamepads.length > 0) {
- console.log('Gamepad initialized successfully.');
- gamepadManager.drawAllGamepads();
- } else {
- console.error('Gamepad initialization failed. Verify canvasId and configuration.');
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement