simplify tilt calculations

This commit is contained in:
Gavin McDonald
2025-07-04 13:59:57 -04:00
parent d3eb6f1b46
commit c6e316a1f8
8 changed files with 91 additions and 84 deletions

View File

@@ -2,6 +2,7 @@
import { createContext, useContext, useEffect, useState } from 'react'; import { createContext, useContext, useEffect, useState } from 'react';
import useSocket from '@/hooks/useSocket'; import useSocket from '@/hooks/useSocket';
import { reduceTilts } from '@/tools';
import { GAME_START, LOCAL_DEFAULTS } from '@/constants'; import { GAME_START, LOCAL_DEFAULTS } from '@/constants';
import type { Dispatch, ReactNode, SetStateAction } from 'react'; import type { Dispatch, ReactNode, SetStateAction } from 'react';
@@ -15,7 +16,7 @@ export interface AppContext {
noGame: boolean; noGame: boolean;
selectCardIndex: number; selectCardIndex: number;
settings: Settings; settings: Settings;
tilt: Tilt[]; tilts: Tilt[];
emitFlip: (cardIndex: number) => void; emitFlip: (cardIndex: number) => void;
emitSettings: (gameData: GameUpdate) => void; emitSettings: (gameData: GameUpdate) => void;
emitRedraw: (cardIndex: number) => void; emitRedraw: (cardIndex: number) => void;
@@ -23,7 +24,7 @@ export interface AppContext {
setGameID: (gameID: string) => void; setGameID: (gameID: string) => void;
setLocalSettings: Dispatch<SetStateAction<LocalSettings>>; setLocalSettings: Dispatch<SetStateAction<LocalSettings>>;
setSelectCardIndex: (cardIndex: number) => void; setSelectCardIndex: (cardIndex: number) => void;
setTilt: (tilt: Tilt[]) => void; setLocalTilt: (tilt: Tilt[]) => void;
} }
export function AppProvider({ children }: { children: ReactNode }) { export function AppProvider({ children }: { children: ReactNode }) {
@@ -32,7 +33,7 @@ export function AppProvider({ children }: { children: ReactNode }) {
const [gameID, setGameID] = useState(''); const [gameID, setGameID] = useState('');
const [noGame, setNoGame] = useState(false); const [noGame, setNoGame] = useState(false);
const [selectCardIndex, setSelectCardIndex] = useState(-1); const [selectCardIndex, setSelectCardIndex] = useState(-1);
const [tilt, setTilt] = useState<Tilt[]>([]); const [localTilt, setLocalTilt] = useState<Tilt[]>([]);
const { emitFlip, emitRedraw, emitSelect, emitSettings, emitTilt } = useSocket({ const { emitFlip, emitRedraw, emitSelect, emitSettings, emitTilt } = useSocket({
gameID, gameID,
@@ -42,17 +43,17 @@ export function AppProvider({ children }: { children: ReactNode }) {
useEffect(() => { useEffect(() => {
if (localSettings.remoteTilt) { if (localSettings.remoteTilt) {
const cardIndex = tilt.findIndex((tilt) => !!tilt); const cardIndex = localTilt.findIndex((tilt) => !!tilt);
if (tilt[cardIndex]) { if (localTilt[cardIndex]) {
emitTilt(cardIndex, tilt[cardIndex]); emitTilt(cardIndex, localTilt[cardIndex]);
} else { } else {
// cardIndex does not matter // cardIndex does not matter
// all tilts for this user will be cleared // all tilts for this user will be cleared
emitTilt(0, { rotateX: 0, rotateY: 0 }); emitTilt(0, { percentX: -1, percentY: -1, rotateX: 0, rotateY: 0 });
} }
} }
}, [tilt, localSettings]); }, [localTilt, localSettings]);
const handleSelect = (cardID: string) => { const handleSelect = (cardID: string) => {
setSelectCardIndex(-1); setSelectCardIndex(-1);
@@ -69,7 +70,7 @@ export function AppProvider({ children }: { children: ReactNode }) {
noGame, noGame,
selectCardIndex, selectCardIndex,
settings: { ...gameData.settings, ...localSettings }, settings: { ...gameData.settings, ...localSettings },
tilt, tilts: reduceTilts(gameData, localTilt),
emitFlip, emitFlip,
emitSettings, emitSettings,
emitRedraw, emitRedraw,
@@ -77,7 +78,7 @@ export function AppProvider({ children }: { children: ReactNode }) {
setGameID, setGameID,
setLocalSettings, setLocalSettings,
setSelectCardIndex, setSelectCardIndex,
setTilt, setLocalTilt,
}; };
return <AppContext.Provider value={appInterface}>{children}</AppContext.Provider>; return <AppContext.Provider value={appInterface}>{children}</AppContext.Provider>;

View File

@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useAppContext } from '@/app/AppContext'; import { useAppContext } from '@/app/AppContext';
import { validTilt } from '@/tools';
const tiltSheen = (sheen: HTMLDivElement, x: number, y: number) => { const tiltSheen = (sheen: HTMLDivElement, x: number, y: number) => {
const rect = sheen.getBoundingClientRect(); const rect = sheen.getBoundingClientRect();
@@ -20,48 +21,21 @@ const tiltSheen = (sheen: HTMLDivElement, x: number, y: number) => {
export default function Sheen({ cardIndex, className }: { cardIndex: number; className?: string }) { export default function Sheen({ cardIndex, className }: { cardIndex: number; className?: string }) {
const sheenRef = useRef<HTMLDivElement>(null); const sheenRef = useRef<HTMLDivElement>(null);
const [untilt, setUntilt] = useState(false); const [untilt, setUntilt] = useState(false);
const { const { tilts } = useAppContext();
gameData,
settings: { tilt, remoteTilt },
tilt: localTilts,
} = useAppContext();
useEffect(() => { useEffect(() => {
const sheen = sheenRef.current; const sheen = sheenRef.current;
if (!sheen) return; if (!sheen) return;
if (tilt) { const tilt = tilts[cardIndex];
const percentX = localTilts[cardIndex]?.percentX || -1;
const percentY = localTilts[cardIndex]?.percentY || -1;
const percentages = remoteTilt if (validTilt(tilt)) {
? [...gameData.tilts[cardIndex], { percentX, percentY }] setUntilt(false);
: [{ percentX, percentY }]; tiltSheen(sheen, tilt.percentX, tilt.percentY);
const { totalX, totalY, count } = percentages
.filter(({ percentX, percentY }) => percentX >= 0 && percentY >= 0)
.reduce(
({ totalX, totalY, count }, { percentX, percentY }) => ({
totalX: totalX + percentX,
totalY: totalY + percentY,
count: ++count,
}),
{ totalX: 0, totalY: 0, count: 0 },
);
if (count && totalX >= 0 && totalY >= 0) {
const x = totalX / count;
const y = totalY / count;
tiltSheen(sheen, x, y);
setUntilt(false);
} else {
setUntilt(true);
}
} else { } else {
setUntilt(true); setUntilt(true);
} }
}, [tilt, localTilts, gameData]); }, [tilts]);
useEffect(() => { useEffect(() => {
const sheen = sheenRef.current; const sheen = sheenRef.current;

View File

@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useAppContext } from '@/app/AppContext'; import { useAppContext } from '@/app/AppContext';
import throttle from '@/tools/throttle'; import { throttle, validTilt } from '@/tools';
import { thirtyFPS } from '@/constants/time'; import { thirtyFPS } from '@/constants/time';
import type { Tilt } from '@/types'; import type { Tilt } from '@/types';
@@ -18,50 +18,21 @@ export default function TiltCard({
}) { }) {
const cardRef = useRef<HTMLDivElement>(null); const cardRef = useRef<HTMLDivElement>(null);
const [untilt, setUntilt] = useState(false); const [untilt, setUntilt] = useState(false);
const { const { settings, tilts, setLocalTilt } = useAppContext();
gameData,
settings: { tilt, remoteTilt },
setTilt,
tilt: localTilts,
} = useAppContext();
useEffect(() => { useEffect(() => {
const card = cardRef.current; const card = cardRef.current;
if (!card) return; if (!card) return;
if (tilt) { const tilt = tilts[cardIndex];
const rotateX = localTilts[cardIndex]?.rotateX || 0;
const rotateY = localTilts[cardIndex]?.rotateY || 0;
const tilts = remoteTilt if (validTilt(tilt)) {
? [...gameData.tilts[cardIndex], { rotateX, rotateY }] setUntilt(false);
: [{ rotateX, rotateY }]; card.style.transform = `rotateX(${tilt.rotateX}deg) rotateY(${tilt.rotateY}deg)`;
} else {
const { totalX, totalY, count } = tilts
.filter(({ rotateX, rotateY }) => !!rotateX && !!rotateY)
.reduce(
({ totalX, totalY, count }, { rotateX, rotateY }) => ({
totalX: totalX + rotateX,
totalY: totalY + rotateY,
count: ++count,
}),
{ totalX: 0, totalY: 0, count: 0 },
);
if (count && (totalX || totalY)) {
setUntilt(false);
const x = totalX / count;
const y = totalY / count;
card.style.transform = `rotateX(${x}deg) rotateY(${y}deg)`;
} else {
setUntilt(true);
}
} else if (card.style.transform !== ZERO_ROTATION) {
setUntilt(true); setUntilt(true);
} }
}, [tilt, localTilts, gameData]); }, [tilts]);
useEffect(() => { useEffect(() => {
const card = cardRef.current; const card = cardRef.current;
@@ -93,17 +64,17 @@ export default function TiltCard({
rotateY, rotateY,
}; };
setTilt(newTilt); setLocalTilt(newTilt);
}, thirtyFPS); }, thirtyFPS);
const handleMouseLeave = () => { const handleMouseLeave = () => {
setTilt([]); setLocalTilt([]);
}; };
return ( return (
<div <div
className={`group ${className}`} className={`group ${className}`}
onMouseMove={tilt ? handleMouseMove : undefined} onMouseMove={settings.tilt ? handleMouseMove : undefined}
onMouseLeave={handleMouseLeave} onMouseLeave={handleMouseLeave}
> >
<div <div

4
tools/index.ts Normal file
View File

@@ -0,0 +1,4 @@
export * from '@/tools/log';
export * from '@/tools/reduceTilts';
export * from '@/tools/throttle';
export * from '@/tools/validTilt';

19
tools/log.tsx Normal file
View File

@@ -0,0 +1,19 @@
/**
* A logging utility designed to be inserted into functional chains.
* Logs all parameters with an optional prefix, then returns the first argument unchanged.
*
* @param {string} [prefix=''] - A label or message to prepend to the logged output.
* @returns {(value: any, ...rest: any[]) => any} - A function that logs its arguments and returns the first one.
*
* @example
* const result = [1, 2, 3]
* .map((n) => n * 2)
* .map(log('doubled:'))
* .filter((n) => n > 2);
*/
export const log =
(prefix: string = ''): ((value: any, ...rest: any[]) => any) =>
(...args: any[]) => {
console.log(prefix, ...args);
return args[0];
};

34
tools/reduceTilts.ts Normal file
View File

@@ -0,0 +1,34 @@
import { log, validTilt } from '@/tools';
import { GameUpdate, Tilt } from '@/types';
const combineTilts = (tilts: Tilt[]) =>
tilts.reduce(
({ pX, pY, rX, rY, count }, { percentX, percentY, rotateX, rotateY }) => ({
pX: pX + percentX,
pY: pY + percentY,
rX: rX + rotateX,
rY: rY + rotateY,
count: count + 1,
}),
{ pX: 0, pY: 0, rX: 0, rY: 0, count: 0 },
);
export function reduceTilts(gameData: GameUpdate, localTilt: Tilt[]): Tilt[] {
const remoteTilts = gameData.tilts;
const tiltEnabled = gameData.settings.tilt;
const remoteTiltEnabled = gameData.settings.remoteTilt;
if (!tiltEnabled) return [];
if (!remoteTiltEnabled) return Array.from({ length: 5 }, (_, i) => localTilt[i]);
return Array.from({ length: 5 }, (_, i) => (localTilt[i] ? [localTilt[i]] : []))
.map((cardTilts, cardIndex) => [...remoteTilts[cardIndex], ...cardTilts])
.map((cardTilts) => cardTilts.filter(validTilt))
.map(combineTilts)
.map(({ pX, pY, rX, rY, count }) => ({
percentX: count ? pX / count : -1,
percentY: count ? pY / count : -1,
rotateX: count ? rX / count : 0,
rotateY: count ? rY / count : 0,
}));
}

View File

@@ -1,4 +1,4 @@
export default function throttle(func: Function, threshold: number) { export function throttle(func: Function, threshold: number) {
let lastCall = 0; let lastCall = 0;
return (...args: any[]) => { return (...args: any[]) => {

4
tools/validTilt.ts Normal file
View File

@@ -0,0 +1,4 @@
import { Tilt } from '@/types';
export const validTilt = ({ percentX, percentY, rotateX, rotateY }: Tilt) =>
percentX >= 0 && percentY >= 0 && !!rotateX && !!rotateY;