game-engine-socket
v1.0.2
Published
NPM module for Multiplayer Games with Socket.IO and WebRTC
Readme
Game Engine Socket Client
A robust, modular React library for real-time multiplayer game development. Simplifies connecting to a custom game server using Socket.IO (with automatic REST fallback) and WebRTC (PeerJS) for peer-to-peer data.
Features
- Socket Client: Singleton managing connection, authentication, and event handling.
- State Synchronization:
useNetworkEntityhook with built-in interpolation for smooth movement. - Room Management: Join, create, list, and sync members in rooms.
- React Components: Ready-to-use components for Chat to verify connection.
- 2D & 3D Support: Components to easily sync
div(2D) or R3Fgroup(3D) transforms.
Installation
npm install game-engine-socketQuick Start
1. Setup Provider
Wrap your application with the GameSocketProvider.
import { GameSocketProvider } from 'game-engine-socket';
const App = () => (
<GameSocketProvider>
<MyGame />
</GameSocketProvider>
);2. Connect & Join
Connect to your server and join a room.
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 (
<div>
{!isConnected ? (
<button onClick={handleConnect}>Connect</button>
) : (
<button onClick={() => joinRoom('lobby')}>Join Lobby</button>
)}
</div>
);
};3. Chat & Messaging
The library includes a pre-built chat component and raw socket events for messaging.
Using the Chat Component:
import { ChatBox } from 'game-engine-socket';
const GameHUD = () => (
<div className="absolute bottom-4 left-4 w-96">
<ChatBox />
</div>
);Listening to Chat Events Manually:
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]);4. Synchronize Entities
Use NetworkTransform2D (for DOM elements) or NetworkTransform3D (for React Three Fiber) to automatically sync position and rotation.
Owner (Your Player):
<NetworkTransform2D
entityId="my-player-id"
isOwner={true}
x={myX}
y={myY}
rotation={myRotation}
>
<div className="player-sprite" />
</NetworkTransform2D>Remote (Other Players):
// Iterate over room members
{currentRoom.members.map(member => (
member.userId !== myId && (
<NetworkTransform2D
key={member.userId}
entityId={`player-${member.userId}`}
isOwner={false}
>
<div className="other-player-sprite" />
</NetworkTransform2D>
)
))}Advanced Usage
Syncing Custom State (Score, Health, Boolean)
You are not limited to positions. You can sync any data type. Primitives (numbers) are interpolated, while booleans and strings are snapped.
const [health, setHealth] = useNetworkEntity<number>({
entityId: 'player-health',
initialState: 100,
isOwner: true,
eventName: 'player:health' // Custom event name to separate traffic
});
// Update health
setHealth(prev => prev - 10);Versatile Interpolation
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):
const [turnData] = useNetworkEntity<TurnData>({
entityId: 'game-turn',
initialState: defaultTurn,
enableInterpolation: false
});API Reference
useGameSocket
client: The underlying SocketClient instance.connect(url, auth): Connect to game server.disconnect(): Disconnect.isConnected: Boolean status.socketId: Current socket ID.
useRoom
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.
useNetworkEntity(options)
Low-level hook for custom sync logic.
state: The interpolated current state.setNetworkState: Function to update state (broadcasts ifisOwneris true).
