extends KinematicBody2D


func damage(arg, id):
	vida += arg
	get_tree().get_nodes_in_group('server')[0]._enemy_dmg(enemy_id)
	if vida <= 0:
		get_tree().get_nodes_in_group('enemy_authority')[0].death_count(id)
		queue_free()

var enemy_id = 0
var type = 0
var fliph = 0
export var vida = 2
# Called when the node enters the scene tree for the first time.

var motion = Vector2(0,50)

var target

func find_target():
	var data = get_tree().get_nodes_in_group('players')
	if data.size() > 0:
		data.shuffle()
		return data[0]

var bullet = preload('res://bullet.tscn')
var firerate = 30
var fireratebuff = 30
var alert = false

func _physics_process(delta):
	if alert:
		if not is_instance_valid(target): return
		if not $RayCast2D.is_colliding():
			fliph = target.global_position.x > global_position.x
			$RayCast2D.cast_to.x = 300 if fliph else -300 
			motion.x = 100 if fliph else -100
			type = 1
		else:
			motion.x = 0
			type = 2
			fireratebuff -= 1
			if fireratebuff == 0:
				var instance = bullet.instance()
				instance.motion.x = 200 if fliph else -200
				instance.global_position = global_position + Vector2(0,-8)
				instance.id = name
				instance.dmg = 10
				instance.target = 'player'
				get_tree().get_nodes_in_group('proj')[0].add_child(instance)
				fireratebuff = firerate
	move_and_slide(motion)


func _on_Area2D_body_entered(body):
	alert = true
	target = body
	pass # Replace with function body.
