extends KinematicBody2D

export var LineColor = Color(1, 0.9, 0.9, 1);
export var Facing = 1;
export var BodyColor = Color(0,0,0,1);
export var speed = 200.9;
export var gravity = 400;
export var jump_factor = 1;
export var terminal_velocity = 400.0;
export var NextLevel = "res://MainScreen.tscn"
var current_speed = Vector2(0,0);
# Declare member variables here. Examples:
# var a = 2
# var b = "text"


# Called when the node enters the scene tree for the first time.
func _ready():
	#set_process(true)
	set_physics_process(true)
	pass # Replace with function body.

func exit():
	get_node("/root/Global").playwin();
	if ( NextLevel == "res://MainScreen.tscn" ) :
		get_node("/root/Global").GameComplete = true;
	get_tree().change_scene(NextLevel)

func kill():
	get_node("/root/Global").playdeath();
	get_tree().reload_current_scene()

func any_ground_cast_colling():
	return ($GroundCast.is_colliding() or $GroundCast2.is_colliding() or $GroundCast3.is_colliding())

func get_landed_on():
	if ($GroundCast.is_colliding()) :
		return $GroundCast.get_collider();
	if ($GroundCast2.is_colliding()) :
		return $GroundCast2.get_collider();
	if ($GroundCast3.is_colliding()) :
		return $GroundCast3.get_collider();


func _physics_process(delta):
	current_speed.y += delta*gravity;
	if ( any_ground_cast_colling() && current_speed.y > 20 ):
		current_speed.y = 20;
		var collided = get_landed_on();
		if ( collided.has_method("landed") ):
			collided.landed()
		if ( collided.has_method("match_down_speed") && collided.match_down_speed() != 0 ):
			current_speed.y = collided.match_down_speed()

	#print(current_speed)	
	if ( current_speed.y > terminal_velocity ) :
		current_speed.y = terminal_velocity;
	if ( Input.is_action_pressed("ui_left") ):
		current_speed.x = speed*-1;
		$Body.scale = Vector2(-1, 1);
		if ( $Anim.current_animation != "Walk" ) :
			$Anim.play("Walk")
	elif ( Input.is_action_pressed("ui_right") ) :
		current_speed.x = speed;
		$Body.scale = Vector2(1,1);
		if ( $Anim.current_animation != "Walk" ) :
			$Anim.play("Walk")
	else:
		current_speed.x = 0;
		if ( $Anim.current_animation != "Idle" ) :
			$Anim.play("Idle")
			
	if ( any_ground_cast_colling() && ( Input.is_action_just_pressed("ui_up") or  Input.is_action_just_pressed("ui_accept") ) ):
		current_speed.y = -1*gravity*jump_factor;
	move_and_slide( current_speed );

func _draw():
	#draw_circle( Vector2(0,0), 36, LineColor );
	#draw_circle( Vector2(0,0), 32, BodyColor );
	pass
# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#	pass
