
extends KinematicBody2D

const WALK_SPEED = 15
const GRAVITY = 600

export var health = 0
export var ricocheting = false
export var can_move = true

var velocity = Vector2()
var is_grounded = false
var move_left = false
var anim = "walk"

func _ready():
	get_node("anim").play(anim)
	if can_move:	
		set_fixed_process(true)
	else:
		get_node("anim").play("look_around")
		get_node("anim").seek(rand_range(0, 1))
	
func _fixed_process(delta):
	velocity.y += delta * GRAVITY
	if move_left:
		velocity.x = -WALK_SPEED
	else:
		velocity.x = WALK_SPEED
	var motion = velocity * delta
	
	if motion != Vector2(0,0):
		motion = move( motion )
		
	if !get_node("sprite/fall_prevent").is_colliding():
		move_left = !move_left 
		var new_scale_x = -get_node("sprite").get_scale().x
		get_node("sprite").set_scale(Vector2(new_scale_x, 1))
		
	if is_colliding():
		var normal = get_collision_normal()
		if normal.y<0:
			is_grounded = true
		motion = normal.slide( motion )
		if abs(normal.x) > 0.1:
			print (normal.x)
			move_left = !move_left 
			var new_scale_x = -get_node("sprite").get_scale().x
			get_node("sprite").set_scale(Vector2(new_scale_x, 1))
		if motion != Vector2(0,0):
			move(motion)
		velocity = normal.slide( velocity )
		
#	if (new_anim !=anim):
#		anim=new_anim
#		anim_node.play(anim)

func apply_damage(var touch_pos, var touch_rot, var damage, var delay):
	if touch_pos.x < 0:
		move_to(get_pos() + Vector2(5, 0))
	else:
		move_to(get_pos() - Vector2(5, 0))
	var particle = get_node("hurt_particle")
	particle.set_param(0, rad2deg(touch_rot + PI/2))
	particle.set_emissor_offset(Vector2(0, touch_pos.y))
	particle.set_emitting(true)
#	if get_node("anim").get_current_animation() == "walk":
#		get_node("anim").play("hurt")
	audio.play_sound("hurt")
	health -= damage
	if health <= 0:
		die()
	
#	if touch_pos.x >0:
#		get_node("anim").play("hurt_a")
#	else:
#		get_node("anim").play("hurt_b")

func die():
	queue_free()
	set_fixed_process(false)
#	get_node("anim").play("death")
	get_node("coll").queue_free()
	audio.play_sound("explosion_2")
	global.show_effect(get_pos(), 2, 1)
	



