Advertisement
Griefchief

Godot 3 4 network property replication multiplayer

May 3rd, 2023
2,301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
GDScript 1.98 KB | Gaming | 0 0
  1. extends Node
  2.  
  3.  
  4. @export var enabled = true
  5. @export var _replicatedNode: NodePath
  6. @onready var replicatedNode:Node = get_node(_replicatedNode)
  7. @export var replicatedValues:Array[String] = []
  8.  
  9. # should be renamed packet_id
  10. var network_id = 0
  11. var last_recieved_network_id = -1
  12. var update_override = false
  13.  
  14. func _ready():
  15.     var parent = self.get_parent()
  16.     if NetworkUtil.is_multiplayer_active() and not parent.is_multiplayer_authority() and enabled:
  17.         rpc("requestUpdate")
  18.  
  19. var old_rep:Array
  20. # Called when the node enters the scene tree for the first time.
  21. func _process(_delta):
  22.     var parent = self.get_parent()
  23.     if NetworkUtil.is_multiplayer_active() and parent.is_multiplayer_authority() and enabled:
  24.         var rep:Array = prep_replicate_values()
  25.         if old_rep == null:
  26.             old_rep = rep
  27.         if update_override or not compareRepArrays(rep, old_rep):
  28.             #FIXME
  29.             #rpc_unreliable("replicate_properties", rep, network_id)
  30.             rpc("replicate_properties", rep, network_id)
  31.         update_override = false
  32.         old_rep = rep
  33.         network_id += 1
  34.         if network_id > 1000000000:
  35.             network_id = 0
  36.  
  37. func prep_replicate_values() -> Array:
  38.     var rep_values = null
  39.    
  40.     var node =  get_node(_replicatedNode)
  41.     if node:
  42.         var size = replicatedValues.size()
  43.         if size > 0:
  44.             rep_values = []
  45.             rep_values.resize(size)
  46.         for i in range(size):
  47.             if replicatedValues[i] in node:
  48.                 rep_values[i] = replicatedNode[replicatedValues[i]]
  49.                 pass
  50.     return rep_values
  51.  
  52. func compareRepArrays(arr1, arr2):
  53.     var size = arr1.size()
  54.     if size == arr2.size():
  55.         for i in range(size):
  56.             if arr1 != arr2:
  57.                 return false
  58.     return true
  59.    
  60. @rpc func requestUpdate():
  61.     update_override = true
  62.  
  63. @rpc("any_peer") func replicate_properties(values:Array, net_id):
  64.     if(last_recieved_network_id < net_id or net_id+100000 < last_recieved_network_id):
  65.         last_recieved_network_id = net_id
  66.         #self.get_parent().set_global_transform(g_transform)
  67.         for i in range(values.size()):
  68.             replicatedNode[replicatedValues[i]] = values[i]
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement