- Notifications
You must be signed in to change notification settings - Fork77
Godot client for Nakama server written in GDScript.
License
heroiclabs/nakama-godot
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Godot client for Nakama server written in GDScript.
Nakama is an open-source server designed to power modern games and apps. Features include user accounts, chat, social, matchmaker, realtime multiplayer, and muchmore.
This client implements the full API and socket options with the server. It's written in GDScript to support Godot Engine4.0+
.
Full documentation is online -https://heroiclabs.com/docs
You're currently looking at the Godot 4 version of the Nakama client for Godot.
If you are using Godot 3, you need to use the'godot-3'branch on GitHub.
You'll need to setup the server and database before you can connect with the client. The simplest way is to use Docker but have a look at theserver documentation for other options.
Install and run the servers. Follow theseinstructions.
Download the client from thereleases page and import it into your project. You can alsodownload it from the asset repository.
Add the
Nakama.gd
singleton (inaddons/com.heroiclabs.nakama/
) as anautoload in Godot.Use the connection credentials to build a client object using the singleton.
extendsNodefunc_ready():varscheme="http"varhost="127.0.0.1"varport=7350varserver_key="defaultkey"varclient:=Nakama.create_client(server_key,host,port,scheme)
The client object has many methods to execute various features in the server or open realtime socket connections with the server.
There's a variety of ways toauthenticate with the server. Authentication can create a user if they don't already exist with those credentials. It's also easy to authenticate with a social profile from Google Play Games, Facebook, Game Center, etc.
varemail="super@heroes.com"varpassword="batsignal"# Use 'await' to wait for the request to complete.varsession :NakamaSession=awaitclient.authenticate_email_async(email,password)print(session)
When authenticated the server responds with an auth token (JWT) which contains useful properties and gets deserialized into aNakamaSession
object.
print(session.token)# raw JWT tokenprint(session.user_id)print(session.username)print("Session has expired:%s"%session.expired)print("Session expires at:%s"%session.expire_time)
It is recommended to store the auth token from the session and check at startup if it has expired. If the token has expired you must reauthenticate. The expiry time of the token can be changed as a setting in the server.
varauthtoken="restored from somewhere"varsession2=NakamaClient.restore_session(authtoken)ifsession2.expired:print("Session has expired. Must reauthenticate!")
NOTE: The length of the lifetime of a session can be changed on the server with the--session.token_expiry_sec
command flag argument.
The client includes lots of builtin APIs for various features of the game server. These can be accessed with the async methods. It can also call custom logic in RPC functions on the server. These can also be executed with a socket object.
All requests are sent with a session object which authorizes the client.
varaccount=awaitclient.get_account_async(session)print(account.user.id)print(account.user.username)print(account.wallet)
Since Godot Engine does not support exceptions, whenever you make an async request via the client or socket, you can check if an error occurred via theis_exception()
method.
varan_invalid_session=NakamaSession.new()# An empty session, which will cause and error when we use it.varaccount2=awaitclient.get_account_async(an_invalid_session)print(account2)# This will print the exceptionifaccount2.is_exception():print("We got an exception")
The client can create one or more sockets with the server. Each socket can have it's own event listeners registered for responses received from the server.
varsocket=Nakama.create_socket_from(client)socket.connected.connect(self._on_socket_connected)socket.closed.connect(self._on_socket_closed)socket.received_error.connect(self._on_socket_error)awaitsocket.connect_async(session)print("Done")func_on_socket_connected():print("Socket connected.")func_on_socket_closed():print("Socket closed.")func_on_socket_error(err):printerr("Socket error%s"%err)
Godot provides aHigh-level MultiplayerAPI,allowing developers to make RPCs, calling functions that run on other peers ina multiplayer match.
For example:
func_process(delta):ifnotis_multiplayer_authority():returnvarinput_vector=get_input_vector()# Move the player locally.velocity=input_vector*SPEEDmove_and_slide()# Then update the player's position on all other connected clients.update_remote_position.rpc(position)@rpc(any_peer)funcupdate_remote_position(new_position):position=new_position
Godot provides a number of built-in backends for sending the RPCs, including:ENet, WebSockets, and WebRTC.
However, you can also use the Nakama client as a backend! This can allow you tocontinue using Godot's familiar High-level Multiplayer API, but with the RPCstransparently sent over a realtime Nakama match.
To do that, you need to use theNakamaMultiplayerBridge
class:
varmultiplayer_bridgefunc_ready():# [...]# You must have a working 'socket', created as described above.multiplayer_bridge=NakamaMultiplayerBridge.new(socket)multiplayer_bridge.match_join_error.connect(self._on_match_join_error)multiplayer_bridge.match_joined.connect(self._on_match_joined)get_tree().get_multiplayer().set_multiplayer_peer(multiplayer_bridge.multiplayer_peer)func_on_match_join_error(error):print ("Unable to join match: ",error.message)func_on_match_join()->void:print ("Joined match with id: ",multiplayer_bridge.match_id)
You can also connect to any of the usual signals onMultiplayerAPI
, forexample:
get_tree().get_multiplayer().peer_connected.connect(self._on_peer_connected)get_tree().get_multiplayer().peer_disconnected.connect(self._on_peer_disconnected)func_on_peer_connected(peer_id):print ("Peer joined match: ",peer_id)func_on_peer_disconnected(peer_id):print ("Peer left match: ",peer_id)
Then you need to join a match, using one of the following methods:
Create a new private match, with your client as the host.
multiplayer_bridge.create_match()
Join a private match.
multiplayer_bridge.join_match(match_id)
Create or join a private match with the given name.
multiplayer_bridge.join_named_match(match_name)
Use the matchmaker to find and join a public match.
varticket=awaitsocket.add_matchmaker_async()ifticket.is_exception():print ("Error joining matchmaking pool: ",ticket.get_exception().message)returnmultiplayer_bridge.start_matchmaking(ticket)
After the the "match_joined" signal is emitted, you can start sending RPCs asusual with therpc()
function, and calling any other functions associated withthe High-level Multiplayer API, such asget_tree().get_multiplayer().get_unique_id()
andnode.set_network_authority(peer_id)
andnode.is_network_authority()
.
If you're using the .NET version of Godot with C# support, you can use theNakama .NET client, which can beinstalled via NuGet:
dotnet add package NakamaClient
This addon includes some C# classes for use with the .NET client, to provide deeperintegration with Godot:
GodotLogger
: A logger which prints to the Godot console.GodotHttpAdapter
: An HTTP adapter which uses Godot's HTTPRequest node.GodotWebSocketAdapter
: A socket adapter which uses Godot's WebSocketClient.
Here's an example of how to use them:
varhttp_adapter=newGodotHttpAdapter();// It's a Node, so it needs to be added to the scene tree.// Consider putting this in an autoload singleton so it won't go away unexpectedly.AddChild(http_adapter);conststringscheme="http";conststringhost="127.0.0.1";constintport=7350;conststringserverKey="defaultkey";// Pass in the 'http_adapter' as the last argument.varclient=newClient(scheme,host,port,serverKey,http_adapter);// To log DEBUG messages to the Godot console.client.Logger=newGodotLogger("Nakama",GodotLogger.LogLevel.DEBUG);ISessionsession;try{session=awaitclient.AuthenticateDeviceAsync(OS.GetUniqueId(),"TestUser",true);}catch(ApiResponseExceptione){GD.PrintErr(e.ToString());return;}varwebsocket_adapter=newGodotWebSocketAdapter();// Like the HTTP adapter, it's a Node, so it needs to be added to the scene tree.// Consider putting this in an autoload singleton so it won't go away unexpectedly.AddChild(websocket_adapter);// Pass in the 'websocket_adapter' as the last argument.varsocket=Socket.From(client,websocket_adapter);
Note:The out-of-the-box Nakama .NET client will work fine with desktop builds of your game! However, it won't work with HTML5 builds, unless you use theGodotHttpAdapter
andGodotWebSocketAdapter
classes.
Satori is a liveops server for games that powers actionable analytics, A/B testing and remote configuration. Use the Satori Godot Client to communicate with Satori from within your Godot game.
Satori is only compatible with Godot 4.
Full documentation is online -https://heroiclabs.com/docs/satori/client-libraries/godot/index.html
Add theSatori.gd
singleton (inaddons/com.heroiclabs.nakama/
) as anautoload in Godot.
Create a client object that accepts the API key you were given as a Satori customer.
extendsNodefuncready():varscheme="http"varhost="127.0.0.1"varport:Int=7450varapiKey="apiKey"varclient:=Satori.create_client(apiKey,host,port,scheme)
Then authenticate with the server to obtain your session.
//AuthenticatewiththeSatoriserver.varsession=await_client.authenticate_async("your-id")ifsession.is_exception():print("Error authenticating: "+session.get_exception()._message)else:print("Authenticated successfully.")
Using the client you can get any experiments or feature flags, the user belongs to.
varexperiments=await_client.get_experiments_async(session, ["experiment1","Experiment2"])varflag=await_client.get_flag_async(session,"FlagName")
You can also send arbitrary events to the server:
var_event=Event.new("gameFinished",Time.get_unix_time_from_system())await_client.event_async(session,_event)
The development roadmap is managed as GitHub issues and pull requests are welcome. If you're interested to improve the code please open an issue to discuss the changes or drop in and discuss it in thecommunity forum.
To run tests you will need to run the server and database. Most tests are written as integration tests which execute against the server. A quick approach we use with our test workflow is to use the Docker compose file described in thedocumentation.
Additionally, you will need to copy (or symlink) theaddons
folder inside thetest_suite
folder. You can now run thetest_suite
project from the Godot Editor.
To run the tests on a headless machine (without a GPU) you can download a copy ofGodot Headless and run it from the command line.
To automate this procedure, move the headless binary totest_suite/bin/godot.elf
, and run the tests via thetest_suite/run_tests.sh
shell script (exit code will report test failure/success).
cd nakamadocker-compose -f ./docker-compose-postgres.yml upcd ..cd nakama-godotsh test_suite/run_tests.sh
To make a new release ready for distribution, simply zip the addons folder recursively (possibly addingCHANGELOG
,LICENSE
, andREADME.md
too).
On unix systems, you can run the following command (replacing$VERSION
with the desired version number). Remember to update theCHANGELOG
file first.
zip -r nakama-$VERSION.zip addons/ LICENSE CHANGELOG.md README.md
This project is licensed under theApache-2 License.
About
Godot client for Nakama server written in GDScript.