Godot addon

Godot 4.2+ addon for connecting a game to a NetStack project. It handles the connection, keeps a local copy of synchronized properties, and lets you call server Functions with await.

Install

  1. Download netstack-godot.zip and extract it into your project, so you have an addons/netstack folder.
  2. Open Project > Project Settings > Plugins and enable NetStack.
  3. Open Project Settings > General > Netstack and fill in your project's address from the dashboard Overview tab.

Enabling the plugin registers a global NetStack client and the project settings below.

Setting Meaning
connection/transport WebSocket (default) or UDP
connection/websocket_url wss://yourgame.netstack.network
connection/udp_host, udp_port yourgame.netstack.network, 7351
connection/api_key Needed for UDP only. Do not ship it in builds that players can download.
session/default_room, default_player_id Used when you call connect_to_room() with no arguments. An empty player ID generates a random one.
session/auto_connect Connect when the game starts
session/auto_reconnect Reconnect with backoff if the connection drops
session/call_timeout Seconds to wait for a Function result

Quick start

func _ready() -> void:
	NetStack.joined.connect(_on_joined)
	NetStack.connect_to_room("lobby-1", "alice")


func _on_joined(room: Dictionary) -> void:
	var result := await NetStack.call_function("useItem", {"itemId": "potion"})
	if result.ok:
		print(result.get_value("remaining"))
	elif result.has_error("ITEM_NOT_OWNED"):
		print("You do not own that item")

call_function always returns a NetStackResult and never throws. Check result.ok, then read result.value, or result.error_code and result.error_message. Besides Function errors, the codes NOT_CONNECTED, CALL_TIMEOUT and DISCONNECTED are produced locally.

Server Functions in GDScript

The Function behind call_function("useItem", ...) can be written in GDScript too. Pick GDScript in the Functions tab and define func run(ctx, args):. The same project can mix GDScript Functions with JavaScript or other languages. See GDScript Functions.

func run(ctx, args):
	var inventory = ctx.player.get("inventory", [])
	if not inventory.has(args.itemId):
		fail("ITEM_NOT_OWNED", "You do not own that item.")
	inventory.erase(args.itemId)
	ctx.player.set("inventory", inventory)
	return { "remaining": inventory.size() }

Events

NetStack.listen("itemUsed", func(data): play_use_animation(data.playerId, data.itemId))
NetStack.server_event.connect(func(name, data): print(name, data))
NetStack.player_joined.connect(spawn_player)
NetStack.player_left.connect(remove_player)

Properties

var round_number = NetStack.get_room_property("round", 0)
var gold = NetStack.get_player_property("gold", "", 0)
var others_hp = NetStack.get_player_property("hp", "bob", 100)

NetStack.property_changed.connect(func(scope, player_id, key, value): print(scope, key, value))

Player properties are private by default, so you only see your own private values. Room properties are public. Global properties arrive as room properties.

JSON numbers arrive as float. Convert with int() when you need an integer.

Nodes

  • NetStackClient: the same client as the global NetStack, as a node. Add one if you want a second connection or per-scene settings.
  • NetStackPropertyBinding: add as a child of a Label, ProgressBar, Sprite2D and so on. Pick a scope and key and it keeps the parent's property updated. format uses {value}, for example Gold: {value}.
  • NetStackEventListener: set event_name and connect its received(data) signal in the editor.
  • NetStackFunctionSubscription: set function_name, args and interval_sec, and connect updated(value) and failed(code, message). It calls the Function on a timer and emits when the answer changes.

Fast-paced movement

func _physics_process(_delta: float) -> void:
	NetStack.send_state({"pos": [position.x, position.y, position.z], "yaw": rotation.y})

func update_other(id: String, node: Node3D) -> void:
	var s := NetStack.get_interpolated_state(id)
	if s.has("pos"):
		node.position = Vector3(s.pos[0], s.pos[1], s.pos[2])

get_player_state(id) returns the newest state, get_server_time_msec() the server clock and get_rtt_msec() the round-trip time. The snapshot_received(tick, states) signal fires when new states arrive. See Fast-paced games.

Every multiplayer tick

network_tick(tick, delta) fires once per server tick while you are in a room (30 times a second; get_tick_rate() returns the exact rate), lined up with the server clock so every player ticks together. Use it for anything that should run at network rate instead of frame rate.

func _ready() -> void:
	NetStack.on_tick(_on_tick)  # same as NetStack.network_tick.connect(_on_tick)


func _on_tick(tick: int, _delta: float) -> void:
	NetStack.send_state({"pos": [position.x, position.y]})
	if tick % 30 == 0:
		print("one second of server time")

get_current_tick() returns the current tick, and off_tick(callable) stops a listener. snapshot_received(tick, states) still fires only for ticks that carried new movement.

Function results and subscriptions

React to a Function's answer wherever it was called from:

NetStack.on_function_result("buyItem", func(result):
	if result.ok:
		coins_label.text = str(result.get_value("coins")))

Or subscribe: the addon calls the Function for you on a timer and runs your callable on the first answer and whenever the answer changes.

var board_sub := NetStack.subscribe_function("getLeaderboard", _show_board, {"top": 10}, 2.0)


func _show_board(result: NetStackResult) -> void:
	if result.ok:
		leaderboard.update(result.value)

# later
NetStack.set_subscription_args(board_sub, {"top": 50})
NetStack.unsubscribe_function(board_sub)

Arguments: Function name, callable, args, interval_sec (default 1; 0 means every tick, at most 5 calls a second) and only_on_change (default true). Calls pause while disconnected and resume after you rejoin. Each call counts toward the 30 messages a second limit, so keep intervals sensible. From the editor, add a NetStackFunctionSubscription node and connect its updated(value) signal.

To react to a single property instead, use watch_property(key, callable, scope, player_id). It sends the current value right away and every change after it.

Ping and blocked networks

ping_label.text = "%d ms" % NetStack.get_ping()      # -1 until the first measurement
NetStack.ping_updated.connect(func(ms): ping_label.text = "%d ms" % ms)
var fresh = await NetStack.measure_ping()            # measure right now

Some ISPs, schools and offices block game servers. check_connectivity() tells the player what is wrong instead of leaving them on a spinner:

NetStack.connection_failed.connect(func(_reason):
	var report = await NetStack.check_connectivity()
	status_label.text = report.message)
status Meaning
ok NetStack is reachable.
blocked The internet works but NetStack does not. Usually an ISP or firewall block; a VPN or mobile data helps.
dns_blocked The network cannot look up NetStack's address. Another DNS server, a VPN or mobile data helps.
offline No internet at all.
unknown The check could not decide, for example in a Web export where the browser blocks it.

await NetStack.is_netstack_blocked() is the yes/no version. The check compares NetStack with connectivity_check_urls (two well-known addresses by default; change them on the node if you prefer others).

All of these are listed on one page in the cheat sheet.

Rooms

NetStack.switch_room("match-4821")
NetStack.leave_room()
NetStack.disconnect_from_server()

Notes

  • Room and player IDs use letters, numbers, underscores and hyphens, up to 64 characters. The addon checks this before connecting.
  • NetStack does not authenticate players. The player ID is a claim.
  • example/inventory_example.gd shows a complete flow against the inventory demo server.