Error while shooting left

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Scavex

Hey guys I made an enemy that moves left and right and shoots the bullets in the direction he moves however with this code when he moves left he shoots the bullet just fine but then I guess the Position2D goes back to right side and the bullet get’s queue freed and it occurs alternatively. For example for every 10 bullets he shoots when he is going left he fires only 5 to the left and other 5 will get queue freed within his collision shape. As for right side he fires perfectly. This is the code :

 func _physics_process(delta):
	if is_dead == false:
		velocity.x=SPEED*direction
		velocity.y+=GRAVITY
		velocity=move_and_slide(velocity, FLOOR)
		$AnimatedSprite.play("Corona")
		Timer += 1
		if Timer > 50:
			Timer = 0
			bulletCount = 0
	
		if Timer < 50 and bulletCount < 1:
			var b = bullet.instance()
			if sign($RayCast2D.position.x)==1:
					b.set_bullet_direction(1)
					print(" Im right")
			else:
					
					$Position2D.position*=Vector2(-1,-1)
					b.set_bullet_direction(-1)
					print(" Im left")
					
			get_parent().add_child(b)
			b.global_position = $Position2D.global_position
			bulletCount += 1

and this here is the code for the set_bullet_direction function :

extends Area2D

const SPEED =300
var velocity = Vector2()
var direction=1

func _ready():
	pass

func set_bullet_direction(dir):
	direction = dir
	if dir==-1:
		$Sprite.flip_h=true
		

func _physics_process(delta):
	velocity.x=SPEED*delta*direction
	translate(velocity)