extends Node2D


# Declare member variables here. Examples:
# var a = 2
# var b = "text"
var animation
var bala
var casquillo
export var looking_at = 1000
export var active = false
# Called when the node enters the scene tree for the first time.
func _ready():
	$"../switch".connect("activate",self,"activate")
	animation = $AnimatedSprite
	bala = $fire/CPUParticles2D
	casquillo = $fire/CPUParticles2D2
	if not active:
		stop_shoot()
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta):
	if active:
		var space_state = $fire.get_world_2d().direct_space_state
		var result = space_state.intersect_ray($fire.global_position,$fire.global_position+Vector2(1,0)*looking_at,[$fire])
		if result:
			if result.collider.get_collision_layer_bit(1) == true:
				shoot(result.collider)
				pass
			pass
		else:
			stop_shoot()
			pass
		pass
	else:
		stop_shoot()

func activate():
	print("torreta activada")
	active = not active
	pass
	
func shoot(target):
	if target.has_method("shooted"):
		target.shooted()
	if not animation.is_playing():
		animation.play()
		bala.emitting = true
		casquillo.emitting = true
		#comenzar a disparar
		pass
	if not $AudioStreamPlayer.playing:
		$AudioStreamPlayer.play()
	pass

func stop_shoot():
	animation.stop()
	(animation as AnimatedSprite).frame = 0
	bala.emitting = false
	casquillo.emitting = false
	if $AudioStreamPlayer.playing:
		$AudioStreamPlayer.stop()


	pass # Replace with function body.
