NPM module for Multiplayer Games with Socket.IO and WebRTC
npm install game-engine-socketuseNetworkEntity hook with built-in interpolation for smooth movement.div (2D) or R3F group (3D) transforms.bash
npm install game-engine-socket
`Quick Start
$3
Wrap your application with the GameSocketProvider.
`tsx
import { GameSocketProvider } from 'game-engine-socket';const App = () => (
);
`$3
Connect to your server and join a room.
`tsx
import { useGameSocket, useRoom } from 'game-engine-socket';const Lobby = () => {
const { connect, isConnected } = useGameSocket();
const { joinRoom } = useRoom();
const handleConnect = () => {
connect('http://localhost:3000', {
apiKey: 'YOUR_API_KEY',
userId: 'unique-user-id'
});
};
return (
{!isConnected ? (
) : (
)}
);
};
`$3
The library includes a pre-built chat component and raw socket events for messaging.Using the Chat Component:
`tsx
import { ChatBox } from 'game-engine-socket';const GameHUD = () => (
);
`Listening to Chat Events Manually:
`tsx
const { client } = useGameSocket();useEffect(() => {
if (!client) return;
client.on('chat', (data) => {
console.log('New message:', data);
// data = { from: 'userId', payload: { text: "Hello" }, ts: 123456... }
});
}, [client]);
`$3
Use NetworkTransform2D (for DOM elements) or NetworkTransform3D (for React Three Fiber) to automatically sync position and rotation.Owner (Your Player):
`tsx
entityId="my-player-id"
isOwner={true}
x={myX}
y={myY}
rotation={myRotation}
>
`Remote (Other Players):
`tsx
// Iterate over room members
{currentRoom.members.map(member => (
member.userId !== myId && (
key={member.userId}
entityId={player-${member.userId}}
isOwner={false}
>
)
))}
`
Advanced Usage
$3
You are not limited to positions. You can sync any data type. Primitives (numbers) are interpolated, while booleans and strings are snapped.`tsx
const [health, setHealth] = useNetworkEntity({
entityId: 'player-health',
initialState: 100,
isOwner: true,
eventName: 'player:health' // Custom event name to separate traffic
});// Update health
setHealth(prev => prev - 10);
`$3
The hook automatically handles interpolation based on type:
- Numbers: Smoothly interpolated (Lerp).
- Objects: Numeric properties are interpolated (x, y, z), others are snapped.
- Booleans/Strings: Snapped immediately.To disable interpolation (e.g., for discrete turn-based data):
`tsx
const [turnData] = useNetworkEntity({
entityId: 'game-turn',
initialState: defaultTurn,
enableInterpolation: false
});
`API Reference
$3
- client: The underlying SocketClient instance.
- connect(url, auth): Connect to game server.
- disconnect(): Disconnect.
- isConnected: Boolean status.
- socketId: Current socket ID.$3
- joinRoom(roomId): Join a room.
- createRoom(roomId?): Create new room.
- leaveRoom(): Leave current room.
- currentRoom: Current room object (id, members, etc).
- rooms: List of available rooms.
- refreshRooms(): Refresh the list.$3
Low-level hook for custom sync logic.
- state: The interpolated current state.
- setNetworkState: Function to update state (broadcasts if isOwner` is true).