
extends KinematicBody2D

const  ROTATION_SPEED = 2

export var guidance = true
export var autodestroy = false
export var autodestroy_time = 0.0
export var speed = 160
export var damage = 200

var target
var target_lost = false

func _fixed_process(delta):
	var tpos = target.get_pos()
	var pos = get_pos()
	
	var ang = get_angle_to(tpos)
	var s = sign(ang)
	ang = abs(ang)
	var nrot = min(ang, ROTATION_SPEED*delta)*s
	rotate(nrot)
	
	var rot = get_rot()
	
	var dir = Vector2(sin(rot), cos(rot)).normalized()
	set_pos(pos + dir * speed * delta)
	
func _on_area_body_enter( body ):
	if body.has_method("apply_damage"):
		var rot = get_rot()
		var corrected_pos = Vector2(get_global_pos() - Vector2(0, 64 * sin(rot)))
#		(touch position, touch angle, damage value, delay)
		body.apply_damage(Vector2(corrected_pos - body.get_pos()), rot, damage, 0)
		_destroy()
	else:
		_destroy()
	
func lose_target():
	var last_target = target
	target = Vector2(rand_range(-1,1), rand_range(-1,1)).normalized()
	var timer = get_node("event_timer")
	timer.set_wait_time(rand_range(2, 4))
	timer.start()
	yield(timer, "timeout")
	target = last_target
	
func _destroy():
	queue_free()
	audio.play_sound("explosion_10")
	global.show_effect(get_pos(), 3, 2)
	global.show_effect(get_pos(), 1, 2)
	
func _ready():
	var rand = rand_range(5,10)
	target = Globals.get("PLAYER")
	set_fixed_process(true)
	if autodestroy:
		var timer = get_node("auto_destroy_timer")
		timer.set_wait_time(rand)
		timer.start()	




