steam-multiplayer-peer icon indicating copy to clipboard operation
steam-multiplayer-peer copied to clipboard

How to get ping?

Open Cretezy opened this issue 8 months ago • 1 comments

Hi, I'd like to be able to display ping between the client and server in my game. Can this library do that?

Cretezy avatar Apr 29 '25 00:04 Cretezy

You could do that using rpcs, with any peer type (enet, webrtc, steam, or any other)

var last_remote_id: int
var last_handshake_id: int
var ping_time_us: int
var pong_time_us: int

func testping(remoteid: int = 1): # test from the client
	last_handshake_id = randi()
	last_remote_id = remoteid
	ping_time_us = Time.get_ticks_usec()
	pong_time_us = ping_time_us
	ping.rpc_id(remoteid, last_handshake_id) # we ping a remote peer by calling the pong rpc on that specific remote peer

	while pong_time_us <= ping_time_us: # await for the response
		await get_tree().process_frame

	var diff_us: int = pong_time_us - ping_time_us # get the time difference
	var diff_ms: int = diff_us / 1000
	print('ping from remote id "%s" was "%s" microsseconds (%s miliseconds)' % [diff_us, diff_ms])

@rpc('any_peer') # this will execute in the remote peer
func ping(handshake_id: int):
	var remote_sender_id: int = multiplayer.get_remote_sender_id()
	pong.rpc_id(remote_sender_id, handshake_id) # the remote peer will answer the ping by calling pong in the sender, with the same handshake id

@rpc('any_peer') # this will execute in the original peer
func pong(handshake_id: int):
	var remote_sender_id: int = multiplayer.get_remote_sender_id()

	if remote_sender_id == last_remote_id: # if pong was called as rpc with the same handshake id, store the current time and reset the last remote peer id and handshake id
		pong_time_us = Time.get_ticks_usec()
		last_remote_id = 0
		last_handshake_id = 0

Gnumaru avatar Oct 20 '25 16:10 Gnumaru