extends KinematicBody2D

signal player_velchange(velocity)

# Declare member variables here. Examples:
# var a = 2
# var b = "text"
var _timer = null

const GRAVITY = 200.0
const WALK_SPEED = 200

var velocity = Vector2()
var old_pos = Vector2()
var since_last_post = 0
var post_interval = 250

var id

# Called when the node enters the scene tree for the first time.
#func _ready():

	
func _physics_process(delta):
	var velocity_old = velocity
	if Input.is_action_pressed("ui_left"):
		velocity.x = -WALK_SPEED
	elif Input.is_action_pressed("ui_right"):
		velocity.x =  WALK_SPEED
	else:
		velocity.x = 0
		
	if Input.is_action_pressed("ui_up"):
		velocity.y = -WALK_SPEED
	elif Input.is_action_pressed("ui_down"):
		velocity.y =  WALK_SPEED
	else:
		velocity.y = 0
		
	if velocity_old != velocity:
		emit_signal("player_velchange", velocity)
		
	# We don't need to multiply velocity by delta because "move_and_slide" already takes delta time into account.
	# The second parameter of "move_and_slide" is the normal pointing up.
	# In the case of a 2D platformer, in Godot, upward is negative y, which translates to -1 as a normal.
	velocity = move_and_slide(velocity, Vector2(0, -1))
	for i in get_slide_count():
		var collision = get_slide_collision(i)
		if collision:
			print(collision)
	
remote func setTarget(targetid, pos):
	#print("setting target for:", targetid)
	if targetid != id:
		get_node("../"+"Player "+str(targetid)).setTarget(targetid, pos)
	
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	since_last_post += delta
	if since_last_post >= post_interval/1000 and get_tree().has_network_peer():
		if old_pos != self.position or since_last_post >= post_interval/100:
			rpc_id(0, "setTarget", get_tree().get_network_unique_id(), self.position)	
			old_pos = self.position		
			since_last_post = 0
