39 lines
776 B
GDScript
39 lines
776 B
GDScript
extends Node
|
|
|
|
signal changed(ping: float)
|
|
|
|
const HISTORY_SIZE = 8
|
|
|
|
var count := 0
|
|
var history: Array[float] = []
|
|
|
|
func _init():
|
|
history.resize(HISTORY_SIZE)
|
|
|
|
func _ready():
|
|
%Network.add_handler(%Network.Packet.PING, self)
|
|
var timer := Timer.new()
|
|
add_child(timer)
|
|
timer.wait_time = 1
|
|
timer.timeout.connect(_ping)
|
|
timer.start()
|
|
|
|
func _ping():
|
|
var buffer := StreamPeerBuffer.new()
|
|
buffer.put_8(%Network.Packet.PING)
|
|
buffer.put_8(count)
|
|
%Network.udp.put_packet(buffer.data_array)
|
|
|
|
history[count] = Time.get_unix_time_from_system()
|
|
count += 1
|
|
|
|
if count >= HISTORY_SIZE:
|
|
count = 0
|
|
|
|
func handle_packet(data: PackedByteArray):
|
|
print("Handled ping!", data)
|
|
var id := data.decode_u8(1)
|
|
var ping := Time.get_unix_time_from_system() - history[id]
|
|
changed.emit(ping)
|
|
|