extends KinematicBody2D

const GRAVITY = 980.0

export (int) var direction = 1 
export var jump_force = 200.0
export var x_jump_force = 10.0
export var jump_time = 2

var velocity = Vector2()
var siding_left = false
var on_floor = true
var jumping = false
var edge = false
var falling = false
var floor_velocity = Vector2()

onready var left_wall = get_node("left_wall_check")
onready var right_wall = get_node("right_wall_check")
onready var edge_check = get_node("edge_check")

func _fixed_process(delta):
	
	velocity.y += GRAVITY * delta
	
	var motion = velocity * delta
	if motion != Vector2(0,0):
		motion = move( motion )
		
	if is_colliding():
		var normal = get_collision_normal()
		if normal.y < 0:
			if normal.y != -1:
				motion.y = 0
			else:
				if !on_floor:
					on_floor = true
					velocity.x = 0
					get_node("anim").play("idle")
				jumping = false
				falling = false
			floor_velocity = get_collider_velocity()
			edge = !edge_check.is_colliding()
		motion = normal.slide( motion ) 
		if motion != Vector2(0,0):
			move(motion)
		velocity = normal.slide( velocity )
	else:
		on_floor = false
		if !jumping and !falling: 
			falling = true
			if abs(velocity.x) < 30:
				velocity.x = 0
				
	if (floor_velocity!=Vector2()):
		move(floor_velocity * delta)
				
	jump_time -= delta
	
	if jump_time <= 0:
		velocity.y = - jump_force
		velocity.x= x_jump_force * direction
		jump_time = 2
		jumping = true
		get_node("anim").play("jump")

	if jumping:
		if right_wall.is_colliding():
			direction = -1
		elif left_wall.is_colliding():
			direction = 1 

func _ready():
	set_fixed_process(true)