All files / src gamepad-source.js

90.9% Statements 20/22
84.61% Branches 11/13
100% Functions 2/2
90.47% Lines 19/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                        16x 16x                 7x 7x   6x 6x       6x   1x 1x   1x 1x   1x 1x       1x   1x 1x       1x   2x       4x      
import { AnalogueSource } from "./analogue-source.js";
 
/**
 * Gamepad implementation of AnalogueSource
 * Maps gamepad axes to ADC channels
 */
export class GamepadSource extends AnalogueSource {
    /**
     * Create a new GamepadSource
     * @param {Function} getGamepads - Function that returns gamepad array
     */
    constructor(getGamepads) {
        super();
        this.getGamepads = getGamepads;
    }
 
    /**
     * Get analog value from gamepad for the specified channel
     * @param {number} channel - The ADC channel (0-3)
     * @returns {number} A value between 0 and 0xffff
     */
    getValue(channel) {
        const pads = this.getGamepads();
        if (!pads || !pads[0]) return 0x8000; // Default center value
 
        const pad = pads[0];
        const pad2 = pads[1];
 
        let rawValue;
 
        switch (channel) {
            case 0:
                rawValue = pad.axes[0];
                break;
            case 1:
                rawValue = pad.axes[1];
                break;
            case 2:
                if (pad2) {
                    rawValue = pad2.axes[0];
                } else E{
                    rawValue = pad.axes[2];
                }
                break;
            case 3:
                if (pad2) {
                    rawValue = pad2.axes[1];
                } else E{
                    rawValue = pad.axes[3];
                }
                break;
            default:
                return 0x8000;
        }
 
        // Scale from [-1, 1] to [0, 0xffff]
        return Math.floor(((1 - rawValue) / 2) * 0xffff);
    }
}