extends KinematicBody2D

export var damage = 0
var ricocheted = false
var velocity = Vector2()

func _ready():
#	print (get_node("pos").get_pos().distance_to(get_node("pos_2").get_pos()))
	velocity = Vector2(600,0).rotated(get_rot()) 
	set_fixed_process(true)
	get_node("auto_destroy_timer").start()

func _fixed_process(delta):
	var motion = velocity * delta
	motion = move( motion )

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)))
		if body.get("ricocheting") and randi() % body.get("armor_class") == 0:
			damage = 0
			ricochet()
			ricocheted = true
		else:
			queue_free()
#		(touch position, touch angle, damage value, delay)
		body.apply_damage(Vector2(corrected_pos - body.get_pos()), rot, damage, 0)
	elif !ricocheted and randi() % 5 == 1:
		ricochet()
		ricocheted = true
	else:
		queue_free()

func ricochet():
	var angle = rand_range(0, 2*PI)
	set_pos(get_node("pos").get_global_pos())
	rotate(angle)
	velocity = Vector2(1000,0).rotated(get_rot()) 
	audio.play_sound("ricochet")

func _on_auto_destroy_timer_timeout():
	queue_free()
