Multiplayer Pong Example (Unreal C++)¶
This page builds a two-player Pong game in Unreal Engine with C++, from a new blank project to a match against another player. The game is one HUD class that draws the court with DrawRect, plus a game mode that uses it, so there are no assets or levels to set up.
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 C++, and name the project Pong. The code below uses the module name PONG_API; if you name the project something else, use YOURNAME_API.
Add the GameFuse plugin¶
- Download the plugin from GitHub (or the Fab store) and put it in your project's
Pluginsfolder, so you havePong/Plugins/GameFuse/GameFuse.uplugin. - Open
Source/Pong/Pong.Build.csand addGameFuseandJsonto the dependencies:
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "GameFuse", "Json" });
- Right-click
Pong.uprojectand choose Generate Visual Studio project files (on a Mac, Generate Xcode project), then open the project. Unreal builds the plugin with it.
The multiplayer client is the UGameFuseMultiplayer game instance subsystem. It uses the engine's WebSockets and HTTP modules, and calls you back on the game thread.
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 or Source.
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:
Write the game client¶
In the editor, choose Tools > New C++ Class, pick HUD as the parent, and name it PongHUD. Replace the two files with these. Put in your own game ID and API token.
Source/Pong/PongHUD.h:
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/HUD.h"
#include "Library/GameFuseMultiplayerTypes.h"
#include "PongHUD.generated.h"
class UGameFuseRoom;
// Two-player Pong on GameFuse Multiplayer: joins a match, sends the mouse as the paddle, draws the court.
UCLASS()
class PONG_API APongHUD : public AHUD
{
GENERATED_BODY()
public:
APongHUD();
virtual void BeginPlay() override;
virtual void Tick(float DeltaSeconds) override;
virtual void DrawHUD() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
private:
void OnSignedIn(bool bSuccess, const FGFMultiplayerError& Error);
void OnJoined(bool bSuccess, UGameFuseRoom* JoinedRoom, const FGFMultiplayerError& Error);
void OnRoomMessage(const FString& Type, const TSharedPtr<FJsonValue>& Data);
UPROPERTY()
TObjectPtr<UGameFuseRoom> Room;
FString MySide; // "left" or "right", from the room's "start" message
FString Status = TEXT("Signing in...");
// What the room last sent, in court pixels (the court is 800 x 500, 0,0 at the top left)
FVector2D Ball = FVector2D(400, 250);
float LeftPaddle = 250;
float RightPaddle = 250;
int32 LeftScore = 0;
int32 RightScore = 0;
float MyPaddle = 250; // where my mouse says my paddle is
float SendTimer = 0;
// Where the court is drawn on screen, worked out in DrawHUD
float CourtScale = 1;
FVector2D CourtOrigin = FVector2D::ZeroVector;
};
Source/Pong/PongHUD.cpp:
#include "PongHUD.h"
#include "Dom/JsonObject.h"
#include "Engine/Canvas.h"
#include "Objects/GameFuseRoom.h"
#include "Subsystems/GameFuseMultiplayer.h"
static const int32 GameId = 123; // your game's ID
static const TCHAR* GameToken = TEXT("your-game-api-token"); // your game's API token
APongHUD::APongHUD()
{
PrimaryActorTick.bCanEverTick = true;
}
void APongHUD::BeginPlay()
{
Super::BeginPlay();
if (APlayerController* Player = GetOwningPlayerController())
{
Player->bShowMouseCursor = true;
}
UGameFuseMultiplayer* Multiplayer = GetGameInstance()->GetSubsystem<UGameFuseMultiplayer>();
Multiplayer->SetGame(GameId, GameToken);
Multiplayer->SignInAsGuest(FGFMultiplayerCallback::CreateUObject(this, &APongHUD::OnSignedIn));
}
void APongHUD::OnSignedIn(bool bSuccess, const FGFMultiplayerError& Error)
{
if (!bSuccess) { Status = Error.Message; return; }
Status = TEXT("Waiting for another player...");
TSharedPtr<FJsonObject> Options = MakeShared<FJsonObject>();
Options->SetStringField(TEXT("clientVersion"), TEXT("1"));
UGameFuseMultiplayer* Multiplayer = GetGameInstance()->GetSubsystem<UGameFuseMultiplayer>();
Multiplayer->JoinQueue(TEXT("pong"), Options, FGFMultiplayerJoinCallback::CreateUObject(this, &APongHUD::OnJoined));
}
void APongHUD::OnJoined(bool bSuccess, UGameFuseRoom* JoinedRoom, const FGFMultiplayerError& Error)
{
if (!bSuccess) { Status = Error.Message; return; }
Room = JoinedRoom;
Room->OnMessageNative.AddUObject(this, &APongHUD::OnRoomMessage);
}
void APongHUD::OnRoomMessage(const FString& Type, const TSharedPtr<FJsonValue>& Data)
{
const TSharedPtr<FJsonObject> Message = Data.IsValid() ? Data->AsObject() : nullptr;
if (!Message.IsValid()) return;
if (Type == TEXT("start"))
{
MySide = Message->GetStringField(TEXT("side"));
Status = FString::Printf(TEXT("You are on the %s. First to %d wins."), *MySide, (int32)Message->GetNumberField(TEXT("pointsToWin")));
}
else if (Type == TEXT("state"))
{
const TSharedPtr<FJsonObject> BallData = Message->GetObjectField(TEXT("ball"));
Ball = FVector2D(BallData->GetNumberField(TEXT("x")), BallData->GetNumberField(TEXT("y")));
LeftPaddle = Message->GetNumberField(TEXT("left"));
RightPaddle = Message->GetNumberField(TEXT("right"));
const TSharedPtr<FJsonObject> Score = Message->GetObjectField(TEXT("score"));
LeftScore = (int32)Score->GetNumberField(TEXT("left"));
RightScore = (int32)Score->GetNumberField(TEXT("right"));
}
else if (Type == TEXT("winner"))
{
Status = Message->GetStringField(TEXT("side")) == MySide
? FString(TEXT("You win!"))
: Message->GetStringField(TEXT("name")) + TEXT(" wins.");
}
}
void APongHUD::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
// The mouse's height over the court is my paddle.
float MouseX, MouseY;
APlayerController* Player = GetOwningPlayerController();
if (Player && Player->GetMousePosition(MouseX, MouseY))
{
MyPaddle = FMath::Clamp((MouseY - CourtOrigin.Y) / CourtScale, 45.f, 455.f);
}
// Send my paddle 20 times a second (the room accepts up to 60 messages a second).
SendTimer += DeltaSeconds;
if (Room && !Room->IsClosed() && !MySide.IsEmpty() && SendTimer >= 0.05f)
{
SendTimer = 0;
TSharedPtr<FJsonObject> Paddle = MakeShared<FJsonObject>();
Paddle->SetNumberField(TEXT("y"), FMath::RoundToInt(MyPaddle));
Room->SendObject(TEXT("paddle"), Paddle);
}
}
void APongHUD::DrawHUD()
{
Super::DrawHUD();
// Fit the 800 x 500 court in the window, under a line of text.
CourtScale = FMath::Min(Canvas->SizeX / 800.f, (Canvas->SizeY - 60.f) / 500.f);
CourtOrigin = FVector2D((Canvas->SizeX - 800.f * CourtScale) / 2.f, 50.f);
auto Box = [this](float X, float Y, float Width, float Height, const FLinearColor& Color)
{
DrawRect(Color, CourtOrigin.X + X * CourtScale, CourtOrigin.Y + Y * CourtScale, Width * CourtScale, Height * CourtScale);
};
DrawText(Status, FLinearColor::White, 20, 15, nullptr, 1.5f);
Box(0, 0, 800, 500, FLinearColor::Black);
const float Left = MySide == TEXT("left") ? MyPaddle : LeftPaddle; // my own paddle follows my mouse at once
const float Right = MySide == TEXT("right") ? MyPaddle : RightPaddle;
Box(24, Left - 45, 12, 90, FLinearColor(0.56f, 0.61f, 1.f));
Box(764, Right - 45, 12, 90, FLinearColor(1.f, 0.54f, 0.3f));
Box(Ball.X - 5, Ball.Y - 5, 10, 10, FLinearColor::White);
DrawText(FString::Printf(TEXT("%d %d"), LeftScore, RightScore), FLinearColor::White,
CourtOrigin.X + 340 * CourtScale, CourtOrigin.Y + 15, nullptr, 2.f);
}
void APongHUD::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
if (Room && !Room->IsClosed()) Room->Leave();
Super::EndPlay(EndPlayReason);
}
Now a game mode that uses the HUD. Make another C++ class with Game Mode Base as the parent, named PongGameMode:
Source/Pong/PongGameMode.h:
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "PongGameMode.generated.h"
UCLASS()
class PONG_API APongGameMode : public AGameModeBase
{
GENERATED_BODY()
public:
APongGameMode();
};
Source/Pong/PongGameMode.cpp:
#include "PongGameMode.h"
#include "PongHUD.h"
APongGameMode::APongGameMode()
{
HUDClass = APongHUD::StaticClass();
}
Build, then in Edit > Project Settings > Maps & Modes set Default GameMode to PongGameMode.
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.