65 lines
1.7 KiB
GDScript
65 lines
1.7 KiB
GDScript
class_name PlayerMove
|
|
extends PacketHandler
|
|
|
|
const updates_per_second := 20.0
|
|
|
|
var delay: float
|
|
var last_sent := Time.get_unix_time_from_system()
|
|
var last_sent_position := Vector3.ZERO
|
|
var last_sent_direction := Vector3.ZERO
|
|
|
|
func _ready():
|
|
delay = 1.0 / updates_per_second
|
|
|
|
func handle_packet(data: PackedByteArray):
|
|
var buffer := StreamPeerBuffer.new()
|
|
buffer.data_array = data
|
|
|
|
var player_id_length := buffer.get_size() - 4 - 4 - 4 - 4
|
|
var player_id := buffer.get_string(player_id_length)
|
|
var x := buffer.get_float()
|
|
var z := buffer.get_float()
|
|
var direction_x := buffer.get_float()
|
|
var direction_z := buffer.get_float()
|
|
|
|
var player := Global.players.get_player(player_id)
|
|
|
|
if !player:
|
|
return
|
|
|
|
var controller := player.controller as ProxyController
|
|
|
|
if !controller:
|
|
return
|
|
|
|
controller.server_position.x = x
|
|
controller.server_position.z = z
|
|
emit.call_deferred(controller, Vector3(direction_x, 0, direction_z))
|
|
|
|
func emit(controller: Controller, direction: Vector3):
|
|
controller.direction_changed.emit(direction)
|
|
|
|
func _process(_delta: float):
|
|
if !Global.player:
|
|
return
|
|
|
|
if Global.player.position == last_sent_position && Global.player.movement.direction == last_sent_direction:
|
|
return
|
|
|
|
if Time.get_unix_time_from_system() < last_sent + delay:
|
|
return
|
|
|
|
send_movement()
|
|
last_sent = Time.get_unix_time_from_system()
|
|
last_sent_position = Global.player.position
|
|
last_sent_direction = Global.player.movement.direction
|
|
|
|
func send_movement():
|
|
var buffer := StreamPeerBuffer.new()
|
|
buffer.put_u8(PacketHandler.Packet.PLAYER_MOVE)
|
|
buffer.put_float(Global.player.position.x)
|
|
buffer.put_float(Global.player.position.z)
|
|
buffer.put_float(Global.player.movement.direction.x)
|
|
buffer.put_float(Global.player.movement.direction.z)
|
|
%Client.send(buffer.data_array)
|