extends KinematicBody

var gravity = Vector3.DOWN * 12  # strength of gravity

var speed = 4  # movement speed

var jump_speed = 6  # jump strength

var spin = 0.1  # rotation speed

var velocity = Vector3()
var jump = false
var old_pos = Vector3()
var since_last_post = 0
var post_interval = 250

func get_input():
	var vy = velocity.y
	velocity = Vector3()
	if Input.is_action_pressed("move_forward"):
		velocity += -transform.basis.z * speed
	if Input.is_action_pressed("move_back"):
		velocity += transform.basis.z * speed
	if Input.is_action_pressed("strafe_right"):
		velocity += transform.basis.x * speed
	if Input.is_action_pressed("strafe_left"):
		velocity += -transform.basis.x * speed
	velocity.y = vy
	
	if Input.is_action_pressed("rotate_ccw"):
		$CameraHub.rotate_y(0.01)
	if Input.is_action_pressed("rotate_cw"):
		$CameraHub.rotate_y(-0.01)
		
	jump = false
	if Input.is_action_just_pressed("jump"):
		jump = true

func _physics_process(delta):
	velocity += gravity * delta
	get_input()
	if jump and is_on_floor():
		velocity.y = jump_speed
	velocity = move_and_slide(velocity, Vector3.UP)
	
func _unhandled_input(event):
	if event is InputEventMouseMotion:
		if event.relative.x > 0:
			rotate_y(-lerp(0, spin, event.relative.x/10))
		elif event.relative.x < 0:
			rotate_y(-lerp(0, spin, event.relative.x/10))

func _process(delta):
	since_last_post += delta
	if since_last_post >= post_interval/1000 and get_tree().has_network_peer():
		if old_pos != self.get_global_transform().origin or since_last_post >= post_interval/100:
			rpc_id(0, "setTarget", get_tree().get_network_unique_id(), self.get_global_transform())	
			old_pos = self.get_global_transform().origin
			since_last_post = 0

remote func setTarget(id, trans):
	get_node("../RemotePlayers/Player "+str(id)).set_target(trans)
