我们可以用rpc_unreliable将当前位置发送出去,再用remote func把位置接收到,实现多人游戏的同步移动。但是这种方法会造成严重的抖动,因为server和client之间是有延迟的。这时我们可以用线性插值来优化移动:
初始化线性插值timer:
var timer = 0.0
接收方法:
remote func _set_position(pos, velo):
position = pos.linear_interpolate(position + velo, timer)
func _physics_process(delta):
timer += delta
timer = clamp(timer, 0, 1)
获取输入的inputVector:
inputVector.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
inputVector.y = Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up")
inputVector = inputVector.normalized()
设置速度:
velocity = inputVector * maxSpeed * delta
利用线性插值实现移动:
position = position.linear_interpolate(position + velocity, timer)
传出位置和速度:
rpc_unreliable("_set_position", position, velocity)
初始化线性插值timer:
var timer = 0.0
接收方法:
remote func _set_position(pos, velo):
position = pos.linear_interpolate(position + velo, timer)
func _physics_process(delta):
timer += delta
timer = clamp(timer, 0, 1)
获取输入的inputVector:
inputVector.x = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")
inputVector.y = Input.get_action_strength("ui_down") - Input.get_action_strength("ui_up")
inputVector = inputVector.normalized()
设置速度:
velocity = inputVector * maxSpeed * delta
利用线性插值实现移动:
position = position.linear_interpolate(position + velocity, timer)
传出位置和速度:
rpc_unreliable("_set_position", position, velocity)