Improved environment

This commit is contained in:
2024-01-16 23:01:16 +01:00
parent 8f0f3d9998
commit 6934f2936b
16 changed files with 274 additions and 96 deletions

View File

@ -1,26 +1,33 @@
extends Node
const PLAYER = preload("res://player/Player.tscn")
@export var playerScene: PackedScene
var logged_in := false
func _ready():
%Network.add_handler(%Network.Packet.LOGIN, self)
%Network.add_handler(Packet.LOGIN, self)
send_login()
func send_login():
if logged_in:
return
var buffer := StreamPeerBuffer.new()
buffer.put_8(%Network.Packet.LOGIN)
buffer.put_8(Packet.LOGIN)
buffer.put_data("password".to_utf8_buffer())
%Network.udp.put_packet(buffer.data_array)
print("Connecting...")
func handle_packet(data: PackedByteArray):
if data[1] != 0:
if data[0] != 0:
print("Login failed.")
return
print("Login succeeded.", data)
spawn_player()
print("Login succeeded.")
logged_in = true
Global.player = spawn_player()
func spawn_player():
var player = PLAYER.instantiate()
add_child(player)
func spawn_player() -> Player:
var player = playerScene.instantiate()
%Players.add_child(player)
return player

View File

@ -3,13 +3,6 @@ extends Node
var udp := PacketPeerUDP.new()
var handlers: Array[Node] = []
enum Packet {
PING = 1,
LOGIN = 2,
LOGOUT = 3,
MOVE = 10,
}
func _init():
handlers.resize(256)
udp.connect_to_host("127.0.0.1", 4242)
@ -19,15 +12,15 @@ func _process(_delta):
return
var packet := udp.get_packet()
var type := packet.decode_u8(0) as Packet
var type := packet.decode_u8(0)
var handler := handlers[type]
if handler == null:
push_warning("Unknown packet type %d" % type)
return
handler.handle_packet(packet)
handler.handle_packet(packet.slice(1))
func add_handler(packet: Packet, node: Node):
func add_handler(packet: int, node: Node):
assert(node.has_method("handle_packet"))
handlers[packet] = node

7
network/Packet.gd Normal file
View File

@ -0,0 +1,7 @@
class_name Packet
enum {
PING = 1,
LOGIN = 2,
LOGOUT = 3,
MOVE = 10,
}

View File

@ -11,16 +11,11 @@ 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()
%Network.add_handler(Packet.PING, self)
func _ping():
func send_ping():
var buffer := StreamPeerBuffer.new()
buffer.put_8(%Network.Packet.PING)
buffer.put_8(Packet.PING)
buffer.put_8(count)
%Network.udp.put_packet(buffer.data_array)
@ -31,8 +26,7 @@ func _ping():
count = 0
func handle_packet(data: PackedByteArray):
print("Handled ping!", data)
var id := data.decode_u8(1)
var id := data.decode_u8(0)
var ping := Time.get_unix_time_from_system() - history[id]
changed.emit(ping)