A bare-bones JavaScript multiplayer game framework that utilises Firebase Realtime Database.
Import PlayOn:
import * as playon from "https://ninjadev64.github.io/PlayOn/playon.js";
Or using vanilla JavaScript:
import("https://ninjadev64.github.io/PlayOn/playon.js").then((playon) => {
// use PlayOn here
});
If you wish to self-host or minify, simply download the library.
Initialise PlayOn:
playon.init(firebaseConfig);
where firebaseConfig
is a Firebase configuration object for a project that has the Realtime Database enabled. For more information see here.
Create a game:
playon.createGame().then((id) => { ... });
PlayOn will handle removing games that are more than a day old automatically.
Join a game:
playon.joinGame(id, username, initialData).then((game) => { ... });
PlayOn will throw errors “GameNotFound” and “UsernameAlreadyTaken” from joinGame
respectively. You should register existing players in your code when joining a game (see below for game.players
).
Updating global data:
game.updateGlobalData({ "gameState": "waiting" });
Updating player-specific data:
game.updatePlayerData({ x: 20, y: 40 });
Data will not be re-written to the database if the contents have not changed. Both methods will not delete existing data, only update the desired values. Any Firebase limitations apply here (e.g. arrays are not supported).
function playerJoined(name, initialData) { ... };
function playerUpdated(name, data) { ... };
function globalDataUpdated(data) { ... };
function connectionChange(connected) { ... };
// game.on(event, function);
game.on("playerJoined", playerJoined);
The below properties should only be read from. Use updateGlobalData
and updatePlayerData
to write to these properties as described above.
game.globalData; // { "gameState": "waiting" }
game.players; // { "ninjadev64": { x: 20, y: 40 } ... }
Call game.leave()
to deregister all internal listeners when the Game object is no longer needed.
See the example folder for an example (live demo). The example uses p5.js and p5play to create a simple movement demo where the current player is highlighted in red.