| name | dev-multiplayer-prediction-movement |
| description | Movement prediction with server reconciliation for WASD controls. Use when implementing player movement. |
| category | multiplayer |
Movement Prediction
WASD movement with client-side prediction and server reconciliation.
When to Use
Use when implementing player movement in multiplayer games:
- FPS/TPS character movement
- WASD movement schemes
- Platformer movement
- Vehicle controls
Client Implementation
import { useRef, useEffect } from '@react-three/fiber';
import { useNetworkManager } from '../../services/NetworkManager';
interface PendingInput {
input: PlayerInput;
sequence: number;
timestamp: number;
}
export function PlayerController() {
const networkManager = useNetworkManager();
const meshRef = useRef<>();
localStateRef = ({
: { : , : , : },
: { : , : , : },
});
pendingInputsRef = useRef<[]>([]);
inputSequenceRef = ();
serverStateRef = ({
: { : , : , : },
: ,
});
( {
unsubscribe = networkManager.( {
localPlayer = serverState..(networkManager.);
(localPlayer) {
(localPlayer);
}
});
unsubscribe;
}, [networkManager]);
() {
serverState = serverStateRef.;
localState = localStateRef.;
pendingInputsRef. = pendingInputsRef..(
p. > serverPlayer.
);
reconciledPosition = { ...serverPlayer. };
( pending pendingInputsRef.) {
reconciledPosition = (
reconciledPosition,
pending.,
);
}
smoothingFactor = ;
localState.. = (
localState..,
reconciledPosition.,
smoothingFactor
);
localState.. = (
localState..,
reconciledPosition.,
smoothingFactor
);
localState.. = (
localState..,
reconciledPosition.,
smoothingFactor
);
}
(): {
speed = .;
result = { ...position };
(input.) result. -= speed * dt;
(input.) result. += speed * dt;
(input.) result. -= speed * dt;
(input.) result. += speed * dt;
result;
}
( {
input = ();
((input)) {
sequence = ++inputSequenceRef.;
pendingInputsRef..({
input,
sequence,
: .(),
});
predictedPosition = (
localStateRef..,
input,
dt
);
localStateRef.. = predictedPosition;
(meshRef.) {
meshRef..(predictedPosition);
}
networkManager.({
: ,
input,
sequence,
});
}
});
(
);
}