How can I make my turret fire automatically without having the player to be inside a detection area

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

Hi, so I made some turrets that work, they do function and their projectiles do what they are supposed to do, but its not the way I want them to work. So you know in super meat boy how it had saw launchers that fired automatically at a certain pace? Well I figured out how to get that pace I want, but I don’t know how to make them fire automatically without the player being there.

extends KinematicBody2D

var can_shoot:= true

export var saw_shot: PackedScene

onready var pointer:= $Pointer
onready var ray:= $Pointer/RayCast2D
onready var shot_timer:= $ShootTimer

func _process(delta):
    shoot()

func shoot()->void:
    if can_shoot and ray.is_colliding():
	    if ray.get_collider().is_in_group("Player"):
		    can_shoot = false
		    shot_timer.start()
		    var temp = saw_shot.instance()
		    add_child(temp)
		    temp.global_position = global_position
		    temp.setup(ray.get_collision_point() - position)

func _on_ShootTimer_timeout():
    can_shoot = true

You can track player position, so you will know if its close to the turret

Then all you have to do find the distance and check if close start the turret, far away stop it

xCode Soul | 2021-06-15 18:01

I don’t want the player to effect the turret firing at all, I want the turrets fire and the player position to be completely separate

AshTheKindra | 2021-06-15 18:05

:bust_in_silhouette: Reply From: codeestuary

It looks like you don’t need to use _process in this case at all.

If you want it to shoot regularly, you can make it shoot everytime the ShootTimer runs out.

Try replacing your _on_ShootTimer_timeout() with this:

func _on_ShootTimer_timeout():

var temp = saw_shot.instance()
add_child(temp)
temp.global_position = global_position
temp.setup(ray.get_collision_point() - position)

Then go to your ShootTimer in the Inspector. Make sure Autostart is on, and One Shot is off.

If you want it to point at the player when it’s in-range, that’s a different question, but hopefully this is what you meant.

(edit: formatting the code to have indents, I hope)

Thank you so much! That works!

AshTheKindra | 2021-06-15 22:24