234 lines
7.8 KiB
TypeScript
234 lines
7.8 KiB
TypeScript
|
|
import React, { useEffect, useState, useRef } from 'react';
|
|
|
|
const XboxController = ({ onGamepadUpdate, handleControlModal, isControlled, isConnecting, hasControlRight }) => {
|
|
const [gamepadState, setGamepadState] = useState<{
|
|
buttons: boolean[];
|
|
axes: number[];
|
|
connected: boolean;
|
|
}>({
|
|
buttons: new Array(17).fill(false),
|
|
axes: [0, 0, 0, 0],
|
|
connected: false,
|
|
});
|
|
|
|
const requestRef = useRef<number>(null);
|
|
const DEAD_ZONE = 0.08;
|
|
|
|
const normalizeAxis = (v: number) =>
|
|
Math.abs(v) < DEAD_ZONE ? 0 : Number(v.toFixed(2));
|
|
const lastSendRef = useRef(0);
|
|
const SEND_INTERVAL = 1000 / 10; // 20Hz
|
|
const lastPayloadRef = useRef('');
|
|
|
|
const updateGamepad = () => {
|
|
const gp = navigator.getGamepads()[0];
|
|
|
|
if (gp) {
|
|
const state = {
|
|
buttons: gp.buttons.map(b => b.pressed),
|
|
axes: gp.axes.map(normalizeAxis),
|
|
connected: true,
|
|
ts: Date.now(),
|
|
};
|
|
|
|
setGamepadState(state);
|
|
|
|
const payload = JSON.stringify({
|
|
buttons: state.buttons,
|
|
axes: state.axes,
|
|
});
|
|
|
|
const now = performance.now();
|
|
|
|
if (
|
|
now - lastSendRef.current > SEND_INTERVAL
|
|
// payload !== lastPayloadRef.current
|
|
) {
|
|
onGamepadUpdate(state); // ✅ 只有这里才发
|
|
lastSendRef.current = now;
|
|
lastPayloadRef.current = payload;
|
|
}
|
|
}
|
|
if (!gp) {
|
|
// 不要在这里停 RAF
|
|
requestRef.current = requestAnimationFrame(updateGamepad);
|
|
return;
|
|
}
|
|
|
|
requestRef.current = requestAnimationFrame(updateGamepad);
|
|
};
|
|
useEffect(() => {
|
|
requestRef.current = requestAnimationFrame(updateGamepad);
|
|
|
|
const onFocus = () => {
|
|
// 页面重新获得焦点 → 立刻重拉一次
|
|
requestRef.current = requestAnimationFrame(updateGamepad);
|
|
};
|
|
|
|
window.addEventListener('focus', onFocus);
|
|
|
|
return () => {
|
|
if (requestRef.current) cancelAnimationFrame(requestRef.current);
|
|
window.removeEventListener('focus', onFocus);
|
|
};
|
|
}, []); // ✅ 空依赖
|
|
|
|
useEffect(() => {
|
|
setTimeout(() => {
|
|
window.focus();
|
|
navigator.getGamepads(); // 🔥 强制触发一次
|
|
}, 0);
|
|
}, [/* 页面切换依赖 */]);
|
|
|
|
useEffect(() => {
|
|
const handleConnect = (e: GamepadEvent) => {
|
|
console.log('🎮 Gamepad connected:', e.gamepad.id);
|
|
setGamepadState(prev => ({ ...prev, connected: true }));
|
|
};
|
|
|
|
const handleDisconnect = (e: GamepadEvent) => {
|
|
console.log('❌ Gamepad disconnected');
|
|
//handleControlModal({ control: false });
|
|
setGamepadState(prev => ({ ...prev, connected: false }));
|
|
};
|
|
|
|
window.addEventListener('gamepadconnected', handleConnect);
|
|
window.addEventListener('gamepaddisconnected', handleDisconnect);
|
|
|
|
return () => {
|
|
window.removeEventListener('gamepadconnected', handleConnect);
|
|
window.removeEventListener('gamepaddisconnected', handleDisconnect);
|
|
};
|
|
}, []);
|
|
|
|
// UI mapping for Xbox Gamepad
|
|
|
|
//点火熄火 上面俩 AB升降底盘 XY割刀加减速 button急停
|
|
// Buttons: 0:A, 1:B, 2:X, 3:Y, 4:LB, 5:RB, 6:LT, 7:RT, 8:Back, 9:Start, 10:LS, 11:RS, 12:Up, 13:Down, 14:Left, 15:Right
|
|
const { buttons, axes, connected } = gamepadState;
|
|
|
|
const getAxisStyle = (axisX: number, axisY: number) => ({
|
|
transform: `translate(${axisX * 6}px, ${axisY * 6}px)`,
|
|
});
|
|
|
|
return (
|
|
<div className="relative w-full aspect-[4/3] flex items-center justify-center "
|
|
onClick={() => {
|
|
if (connected && !isControlled && hasControlRight) {
|
|
console.log("点击了无控制权限,发起权限请求");
|
|
// 示例:调用你代码中已有的权限请求弹窗逻辑
|
|
handleControlModal({ control: true, type: "switchPermission" });
|
|
}
|
|
}}>
|
|
{/* Gamepad Status Badge */}
|
|
<div
|
|
className={`absolute top-0 right-0 px-2 py-0.5 rounded text-[8px] font-bold tracking-widest border
|
|
${connected || !hasControlRight
|
|
? isConnecting
|
|
? 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30'
|
|
: isControlled
|
|
? 'bg-cyan-500/20 text-cyan-400 border-cyan-500/30'
|
|
: 'bg-red-500/20 text-red-400 border-red-500/30'
|
|
: 'bg-slate-800 text-slate-500 border-white/5'
|
|
}
|
|
`}
|
|
>
|
|
{!connected ? (
|
|
'未连接设备'
|
|
) : !hasControlRight ? (
|
|
'其他 Web 端已连接'
|
|
) : isConnecting ? (
|
|
'请求控制中...'
|
|
) : isControlled ? (
|
|
'控制中'
|
|
) : (
|
|
'点击获取控制权限'
|
|
)}
|
|
</div>
|
|
|
|
<svg viewBox="0 0 400 300" className="w-full h-full drop-shadow-[0_0_20px_rgba(34,211,238,0.15)]">
|
|
{/* Main Body */}
|
|
<path
|
|
d="M100 80 Q50 80 40 130 L30 220 Q25 270 80 280 L140 250 L260 250 L320 280 Q375 270 370 220 L360 130 Q350 80 300 80 Z"
|
|
fill="#1e293b"
|
|
stroke={connected ? "#22d3ee" : "#334155"}
|
|
strokeWidth="3"
|
|
transform="scale(1, 1.08)"
|
|
transformOrigin="200px 180px"
|
|
/>
|
|
|
|
{/* Triggers & Bumpers */}
|
|
<rect x="70" y="50" width="50" height="25" rx="5" fill={buttons[4] ? "#22d3ee" : "#0f172a"} stroke="#22d3ee" strokeWidth="1" opacity={buttons[4] ? 1 : 0.3} />
|
|
<rect x="280" y="50" width="50" height="25" rx="5" fill={buttons[5] ? "#22d3ee" : "#0f172a"} stroke="#22d3ee" strokeWidth="1" opacity={buttons[5] ? 1 : 0.3} />
|
|
|
|
{/* LT / RT Indicators */}
|
|
<path d="M80 30 L110 30 Q115 45 95 50 L80 50 Z" fill={buttons[6] ? "#22d3ee" : "transparent"} stroke="#22d3ee" strokeWidth="1" opacity={buttons[6] ? 1 : 0.2} />
|
|
<path d="M320 30 L290 30 Q285 45 305 50 L320 50 Z" fill={buttons[7] ? "#22d3ee" : "transparent"} stroke="#22d3ee" strokeWidth="1" opacity={buttons[7] ? 1 : 0.2} />
|
|
|
|
{/* Left Stick Area */}
|
|
<circle cx="120" cy="140" r="35" fill="#0f172a" stroke="#22d3ee" strokeWidth="1" strokeDasharray="2 2" />
|
|
<g style={getAxisStyle(axes[0] || 0, axes[1] || 0)}>
|
|
<circle cx="120" cy="140" r="28" fill="#1e293b" stroke="#22d3ee" strokeWidth="2" />
|
|
<circle cx="120" cy="140" r="12" fill={buttons[10] ? "#22d3ee" : "transparent"} stroke="#22d3ee" strokeWidth="1" />
|
|
</g>
|
|
|
|
{/* Right Stick Area */}
|
|
<g transform="translate(0, 20)">
|
|
<circle
|
|
cx="280"
|
|
cy="200"
|
|
r="35"
|
|
fill="#0f172a"
|
|
stroke="#22d3ee"
|
|
strokeWidth="1"
|
|
strokeDasharray="2 2"
|
|
/>
|
|
|
|
<g style={getAxisStyle(axes[2] || 0, axes[3] || 0)}>
|
|
<circle
|
|
cx="280"
|
|
cy="200"
|
|
r="28"
|
|
fill="#1e293b"
|
|
stroke="#22d3ee"
|
|
strokeWidth="2"
|
|
/>
|
|
<circle
|
|
cx="280"
|
|
cy="200"
|
|
r="12"
|
|
fill={buttons[11] ? "#22d3ee" : "transparent"}
|
|
stroke="#22d3ee"
|
|
strokeWidth="1"
|
|
/>
|
|
</g>
|
|
</g>
|
|
|
|
{/* D-Pad */}
|
|
<g transform="translate(130, 220)">
|
|
<path d="M0 -25 L0 25 M-25 0 L25 0" stroke="#334155" strokeWidth="15" strokeLinecap="round" />
|
|
<path d="M0 -25 L0 -10" stroke={buttons[12] ? "#22d3ee" : "#64748b"} strokeWidth="12" strokeLinecap="round" />
|
|
<path d="M0 25 L0 10" stroke={buttons[13] ? "#22d3ee" : "#64748b"} strokeWidth="12" strokeLinecap="round" />
|
|
<path d="M-25 0 L-10 0" stroke={buttons[14] ? "#22d3ee" : "#64748b"} strokeWidth="12" strokeLinecap="round" />
|
|
<path d="M25 0 L10 0" stroke={buttons[15] ? "#22d3ee" : "#64748b"} strokeWidth="12" strokeLinecap="round" />
|
|
</g>
|
|
|
|
{/* Buttons (ABXY) */}
|
|
<g transform="translate(280, 140)">
|
|
<circle cx="0" cy="20" r="12" fill={buttons[0] ? "#22c55e" : "#0f172a"} stroke="#22c55e" strokeWidth="1" opacity={buttons[0] ? 1 : 0.6} /> {/* A */}
|
|
<circle cx="20" cy="0" r="12" fill={buttons[1] ? "#ef4444" : "#0f172a"} stroke="#ef4444" strokeWidth="1" opacity={buttons[1] ? 1 : 0.6} /> {/* B */}
|
|
<circle cx="-20" cy="0" r="12" fill={buttons[2] ? "#3b82f6" : "#0f172a"} stroke="#3b82f6" strokeWidth="1" opacity={buttons[2] ? 1 : 0.6} /> {/* X */}
|
|
<circle cx="0" cy="-20" r="12" fill={buttons[3] ? "#eab308" : "#0f172a"} stroke="#eab308" strokeWidth="1" opacity={buttons[3] ? 1 : 0.6} /> {/* Y */}
|
|
</g>
|
|
|
|
{/* Menu Buttons */}
|
|
<circle cx="180" cy="140" r="6" fill={buttons[8] ? "#22d3ee" : "#334155"} />
|
|
<circle cx="220" cy="140" r="6" fill={buttons[9] ? "#22d3ee" : "#334155"} />
|
|
</svg>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default XboxController;
|