Multiplayer Pong Example (Unreal Blueprints)¶
This page builds a two-player Pong game in Unreal Engine with Blueprints only, from a new blank project to a match against another player. The court is one Widget Blueprint; the networking is a handful of GameFuse Multiplayer nodes.
Prefer C++? The same game is on the Unreal C++ page.
Before you start¶
You need:
- A GameFuse account and a game. The game's page on the dashboard shows its game ID and API token.
- Multiplayer switched on for the game, and its upload key. Both are on the game's Multiplayer tab.
- Node.js 20 or later, for the
gamefusecommand that uploads your room code.
The game has two halves:
| Part | Runs on | What it does |
|---|---|---|
Room code (room.js) |
GameFuse's multiplayer servers | Moves the ball, bounces it, keeps the score, picks the winner. The same file for every engine. |
| Game client | Each player's computer | Draws the court, sends where the player's paddle is, shows what the room sends back. |
The room owns the ball and the score, so a player cannot cheat by changing them. Each player only sends one thing: where their paddle is.
Make the project¶
In the Unreal Project Browser choose Games > Blank, pick Blueprint, and name the project Pong. Unreal 5.1 or later.
Add the plugins¶
- Download the GameFuse plugin from GitHub (or the Fab store) and put it in your project's
Pluginsfolder, so you havePong/Plugins/GameFuse/GameFuse.uplugin. Restart the editor and let it build the plugin. - In Edit > Plugins, turn on GameFuse and Json Blueprint Utilities (it comes with Unreal). Restart when asked.
The room sends its messages as JSON text. Json Blueprint Utilities gives you the Load Json from String and Get Field nodes that read it.
Write the room code¶
The room code is one JavaScript file that GameFuse runs for every match. It is the same for every engine, so a Unreal player can play against a browser, Unity or Unreal player.
Install the gamefuse command once:
In your project folder, make the room code folder. --game-mode pong is the queue name the game client joins; put in your own game ID:
That makes a folder called pong-pong-gamefuse-multiplayer with a starter room.js and a .env file. Replace pong-pong-gamefuse-multiplayer/room.js with this:
// Pong for two players. The room owns the ball and the score, so nobody can cheat;
// each player only sends where their own paddle is.
// This is the room code used by every "Multiplayer Pong Example" page in the docs.
const WIDTH = 800;
const HEIGHT = 500;
const PADDLE_HEIGHT = 90;
const PADDLE_X = 30; // how far each paddle is from its wall
const BALL_SPEED = 300; // pixels per second when served
const POINTS_TO_WIN = 5;
export default {
config: {
minPlayers: 2,
maxPlayers: 2,
tickRate: 30, // update() runs 30 times a second
reconnectSeconds: 15, // a dropped player gets 15 seconds to come back
},
start(room) {
const [left, right] = room.players; // the first player in is on the left
room.state.sides = { [left.id]: 'left', [right.id]: 'right' };
room.state.paddles = { left: HEIGHT / 2, right: HEIGHT / 2 };
room.state.score = { left: 0, right: 0 };
serve(room, 1);
// Tell each player which side they are on.
room.send(left, 'start', { side: 'left', width: WIDTH, height: HEIGHT, pointsToWin: POINTS_TO_WIN });
room.send(right, 'start', { side: 'right', width: WIDTH, height: HEIGHT, pointsToWin: POINTS_TO_WIN });
},
update(room, dt) {
const s = room.state;
if (!s.ball || s.over) return;
const ball = s.ball;
ball.x += ball.vx * dt;
ball.y += ball.vy * dt;
// Bounce off the top and bottom walls.
if (ball.y < 0) { ball.y = 0; ball.vy = Math.abs(ball.vy); }
if (ball.y > HEIGHT) { ball.y = HEIGHT; ball.vy = -Math.abs(ball.vy); }
// Bounce off a paddle. Hitting near the end of a paddle sends the ball off at an angle.
hitPaddle(ball, PADDLE_X, s.paddles.left, -1);
hitPaddle(ball, WIDTH - PADDLE_X, s.paddles.right, 1);
// Past a paddle: a point for the other side.
if (ball.x < 0) point(room, 'right');
if (ball.x > WIDTH) point(room, 'left');
room.broadcast('state', {
ball: { x: Math.round(ball.x), y: Math.round(ball.y) },
left: Math.round(s.paddles.left),
right: Math.round(s.paddles.right),
score: s.score,
});
},
message(room, player, type, data) {
if (type !== 'paddle' || !room.state.sides) return;
const side = room.state.sides[player.id];
const y = Number(data && data.y);
if (!side || !Number.isFinite(y)) return;
room.state.paddles[side] = Math.max(PADDLE_HEIGHT / 2, Math.min(HEIGHT - PADDLE_HEIGHT / 2, y));
},
playerLeft(room, player, how) {
// A player quit, or dropped and did not come back in time: the other one wins.
if (!room.state.sides || room.state.over) return;
const other = room.players.find((p) => p.id !== player.id);
if (other) finish(room, other);
},
async gameEnd(room, result) {
if (result.winnerId) await room.gamefuse.users.addScore(result.winnerId, 1);
},
};
function serve(room, direction) {
room.state.ball = {
x: WIDTH / 2,
y: HEIGHT / 2,
vx: BALL_SPEED * direction,
vy: BALL_SPEED * (Math.random() - 0.5),
};
}
// side: -1 for the left paddle, 1 for the right. Only bounces a ball moving toward that paddle.
function hitPaddle(ball, paddleX, paddleY, side) {
const movingToward = side < 0 ? ball.vx < 0 : ball.vx > 0;
const closeInX = Math.abs(ball.x - paddleX) < 12;
const closeInY = Math.abs(ball.y - paddleY) < PADDLE_HEIGHT / 2 + 6;
if (!movingToward || !closeInX || !closeInY) return;
ball.vx = -ball.vx * 1.05; // a little faster every hit
ball.vy += (ball.y - paddleY) * 5;
}
function point(room, side) {
const s = room.state;
s.score[side] += 1;
room.broadcast('point', { side, score: s.score });
if (s.score[side] >= POINTS_TO_WIN) {
const winnerId = Object.keys(s.sides).find((id) => s.sides[id] === side);
finish(room, room.players.find((p) => String(p.id) === winnerId));
return;
}
serve(room, side === 'left' ? 1 : -1); // serve toward the player who lost the point
}
function finish(room, winner) {
room.state.over = true;
const side = room.state.sides[winner.id];
room.broadcast('winner', { side, name: winner.name });
room.end({ winnerId: winner.id });
}
What each part does:
configasks for 2 players, runsupdate30 times a second, and holds a dropped player's seat for 15 seconds.startruns once both players are in. The first player in plays on the left. Each player is told their side.updatemoves the ball, bounces it off the walls and paddles, scores points, and sends every player astatemessage: the ball, both paddles and the score.messagetakes a player'spaddlemessage and moves only that player's paddle, kept on the court.playerLeftgives the match to the other player if someone quits or does not come back in time.gameEndadds 1 to the winner's GameFuse score afterroom.end.
The messages, which every game client below uses:
| Message | Who sends it | Data |
|---|---|---|
start |
room, to each player | { side: "left" or "right", width: 800, height: 500, pointsToWin: 5 } |
state |
room, 30 times a second | { ball: { x, y }, left, right, score: { left, right } } (left and right are the middles of the paddles) |
point |
room | { side, score }: who scored |
winner |
room | { side, name } |
paddle |
each player, up to 20 times a second | { y }: the middle of their paddle, 45 to 455 |
The court is 800 by 500, with (0, 0) at the top left. The paddles are 90 tall and 30 in from each wall.
Make the room code folder next to your Unreal project folder, not inside Content.
Upload the room code to GameFuse¶
Open the .env file that init made in your project folder and put in your upload key from the game's Multiplayer tab:
# .env (keep it out of git: it holds a secret)
GAMEFUSE_UPLOAD_KEY=mpk_your_upload_key
GAMEFUSE_GAME_ID=123
init already added .env to your .gitignore. Never put the upload key in your game.
Check the room code, then upload it:
validate runs the same check GameFuse's servers run and uploads nothing. deploy checks, uploads and makes it the live version for the pong queue. New matches use it at once.
To see what your room code logs while you play:
Make the court widget¶
Two structs for the messages¶
In the Content Browser, Add > Blueprint > Structure:
| Struct | Variables |
|---|---|
S_PongPoint |
X (Float), Y (Float) |
S_PongScore |
Left (Integer), Right (Integer) |
Get Field fills a struct from a JSON object by matching names, so {"x": 400, "y": 250} becomes an S_PongPoint.
The widget¶
Add > User Interface > Widget Blueprint, pick User Widget, name it WBP_Pong, and open it. In the Designer:
- Add a Canvas Panel. Inside it add a Text Block named
StatusTextat the top left. - Add a Scale Box filling the screen under the text (anchors: full screen, top offset 40). Inside it add a Canvas Panel named
Court, and give the Scale Box's child a fixed size with a Size Box of width 800 and height 500 so the court is always 800 by 500 and scaled to fit. - In
Courtadd, each with position (0, 0) and alignment (0, 0):- an Image named
Background, size 800 x 500, black; - an Image named
LeftPaddle, size 12 x 90, position (24, 0), light blue; - an Image named
RightPaddle, size 12 x 90, position (764, 0), orange; - an Image named
Ball, size 10 x 10, white; - a Text Block named
ScoreTextat (340, 10), size 30.
- an Image named
- Tick Is Variable on
StatusText,LeftPaddle,RightPaddle,BallandScoreText.
Paddles and the ball are moved with Set Render Translation, so their position (0, 0) is where a translation of zero puts them.
The widget's variables¶
In the Graph, add these variables:
| Variable | Type | Default |
|---|---|---|
Room |
GameFuse Room (Object Reference) | |
MySide |
String | |
MyPaddle |
Float | 250 |
Write the game client¶
All of this is in WBP_Pong's Graph. Put in your own game ID and API token.
1. Sign in and join the queue¶
From Event Construct:
- Get Owning Player → Set Show Mouse Cursor (true).
- Get Game Instance → Get Subsystem (class GameFuse Multiplayer).
- From the subsystem: Set Game (In Game Id
123, In Game Tokenyour-game-api-token). - Then Sign In As Guest. Drag off its Callback pin, choose Add Custom Event, and name it
OnSignedIn. It getsbSuccessandError. - Set Text on
StatusText: "Signing in...".
In OnSignedIn:
- Branch on
bSuccess. False: Set Text onStatusTexttoError→ Message, and stop. - True: Set Text on
StatusText: "Waiting for another player...". - The GameFuse Multiplayer subsystem again → Join Queue with Queue
pongand Options Json{"clientVersion":"1"}. From its Callback, Add Custom Event namedOnJoined. It getsbSuccess,RoomandError.
In OnJoined:
- Branch on
bSuccess. False: showError→ Message inStatusText. - True: Set the
Roomvariable from the event'sRoom. - From
Room: Bind Event to On Message. From its Event pin, Add Custom Event namedOnRoomMessage. It getsTypeandDataJson. - Set Timer by Event: Time
0.05, Looping ticked. From its Event pin, Add Custom Event namedSendPaddle.
2. Read the room's messages¶
In OnRoomMessage:
- Load Json from String with
DataJson. Its Json Object output is used by every Get Field below. - Switch on String on
Type, with casesstart,stateandwinner.
start:
- Get Field (Field Name
side), output into a String → SetMySide. - Set Text on
StatusText: Format TextYou are on the {side}. First to 5 wins.
state (30 times a second):
- Get Field
ball→ anS_PongPoint. Set Render Translation onBallto (X − 5, Y − 5). - Get Field
left→ a Float. IfMySideisleft, useMyPaddleinstead (your own paddle follows your mouse at once). Set Render Translation onLeftPaddleto (0, value − 45). - Get Field
right→ a Float, the same way withrightandRightPaddle. - Get Field
score→ anS_PongScore. Set Text onScoreText: Format Text{Left} {Right}.
winner:
- Get Field
side→ a String, and Get Fieldname→ a String. - If
sideequalsMySide, Set Text onStatusTextto "You win!", otherwise toname+ " wins.".
3. Send the paddle¶
On Event Tick:
- Find the mouse over the court:
Court→ Get Cached Geometry → Absolute to Local, with Get Mouse Position on Platform as the absolute position. The result is in court pixels, becauseCourtis 800 x 500 however big it is drawn. - Take its Y → Clamp (Float) between 45 and 455 → Set
MyPaddle.
In SendPaddle (20 times a second, from the timer):
- Branch: only if
RoomIs Valid,Room→ Is Closed is false, andMySideis not empty. Room→ Send (JSON) with Typepaddleand Data Json from Format Text{"y":{y}}withMyPaddlerounded (Round) intoy, then To String.
The room accepts up to 60 messages a second; 20 is plenty.
4. Show the widget¶
Open the level's Blueprint (Blueprints > Open Level Blueprint). On Event BeginPlay: Create Widget (class WBP_Pong) → Add to Viewport.
Play it¶
Press Play. The game signs in and shows "Waiting for another player...".
You need a second player who is not the same guest. The plugin saves the guest in GameUserSettings.ini, so a second copy on the same computer is the same player. The quickest opponents:
- the JavaScript version in a browser, with the same game ID and token;
- the computer player from the REST API version:
node bot.js; - or a packaged build on a second computer.
They all join the same pong queue, so they are matched with your Unreal game. Move the mouse up and down over the court. First to 5 wins, and the winner gets 1 point on their GameFuse score.
Next¶
- Play with a friend by code instead of a queue: matchmaking and private room codes.
- Everything room code can do: room code reference.
- What happens when wifi drops: connection drops and rejoining.
- The same game in another engine: JavaScript, Unity C#, Unreal C++, Unreal Blueprints, REST API.