Skip to content
Download all docs .md

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 gamefuse command 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

  1. Download the GameFuse plugin from GitHub (or the Fab store) and put it in your project's Plugins folder, so you have Pong/Plugins/GameFuse/GameFuse.uplugin. Restart the editor and let it build the plugin.
  2. 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:

npm i -g gamefuse

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:

gamefuse multiplayer init --game-name pong --game-mode pong --game 123

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:

  • config asks for 2 players, runs update 30 times a second, and holds a dropped player's seat for 15 seconds.
  • start runs once both players are in. The first player in plays on the left. Each player is told their side.
  • update moves the ball, bounces it off the walls and paddles, scores points, and sends every player a state message: the ball, both paddles and the score.
  • message takes a player's paddle message and moves only that player's paddle, kept on the court.
  • playerLeft gives the match to the other player if someone quits or does not come back in time.
  • gameEnd adds 1 to the winner's GameFuse score after room.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:

gamefuse multiplayer validate
gamefuse multiplayer deploy

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:

gamefuse multiplayer logs --follow

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:

  1. Add a Canvas Panel. Inside it add a Text Block named StatusText at the top left.
  2. 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.
  3. In Court add, 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 ScoreText at (340, 10), size 30.
  4. Tick Is Variable on StatusText, LeftPaddle, RightPaddle, Ball and ScoreText.

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:

  1. Get Owning Player → Set Show Mouse Cursor (true).
  2. Get Game Instance → Get Subsystem (class GameFuse Multiplayer).
  3. From the subsystem: Set Game (In Game Id 123, In Game Token your-game-api-token).
  4. Then Sign In As Guest. Drag off its Callback pin, choose Add Custom Event, and name it OnSignedIn. It gets bSuccess and Error.
  5. Set Text on StatusText: "Signing in...".

In OnSignedIn:

  1. Branch on bSuccess. False: Set Text on StatusText to Error → Message, and stop.
  2. True: Set Text on StatusText: "Waiting for another player...".
  3. The GameFuse Multiplayer subsystem again → Join Queue with Queue pong and Options Json {"clientVersion":"1"}. From its Callback, Add Custom Event named OnJoined. It gets bSuccess, Room and Error.

In OnJoined:

  1. Branch on bSuccess. False: show Error → Message in StatusText.
  2. True: Set the Room variable from the event's Room.
  3. From Room: Bind Event to On Message. From its Event pin, Add Custom Event named OnRoomMessage. It gets Type and DataJson.
  4. Set Timer by Event: Time 0.05, Looping ticked. From its Event pin, Add Custom Event named SendPaddle.

2. Read the room's messages

In OnRoomMessage:

  1. Load Json from String with DataJson. Its Json Object output is used by every Get Field below.
  2. Switch on String on Type, with cases start, state and winner.

start:

  1. Get Field (Field Name side), output into a String → Set MySide.
  2. Set Text on StatusText: Format Text You are on the {side}. First to 5 wins.

state (30 times a second):

  1. Get Field ball → an S_PongPoint. Set Render Translation on Ball to (X − 5, Y − 5).
  2. Get Field left → a Float. If MySide is left, use MyPaddle instead (your own paddle follows your mouse at once). Set Render Translation on LeftPaddle to (0, value − 45).
  3. Get Field right → a Float, the same way with right and RightPaddle.
  4. Get Field score → an S_PongScore. Set Text on ScoreText: Format Text {Left} {Right}.

winner:

  1. Get Field side → a String, and Get Field name → a String.
  2. If side equals MySide, Set Text on StatusText to "You win!", otherwise to name + " wins.".

3. Send the paddle

On Event Tick:

  1. 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, because Court is 800 x 500 however big it is drawn.
  2. Take its Y → Clamp (Float) between 45 and 455 → Set MyPaddle.

In SendPaddle (20 times a second, from the timer):

  1. Branch: only if Room Is Valid, Room → Is Closed is false, and MySide is not empty.
  2. Room → Send (JSON) with Type paddle and Data Json from Format Text {"y":{y}} with MyPaddle rounded (Round) into y, 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