How would I remove my bullets after they've travelled a certain distance?

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

Hey guys, I have a shotgun programmed in that works how I want but I would like the bullets to stop and have the gun be short range. How would I go about removing them after the go a certain distance?

Thanks in advance!

code: Screenshot - 6613b125c6e39d28a810c1af0b31285e - Gyazo
gif: Screen capture - 1bfc5f895452ae03d02f803f29d8e3c1 - Gyazo

:bust_in_silhouette: Reply From: dustin

Save the starting position when the bullet spawns, and if the current position > starting position + preferred distance, queue free.

example (use these scripts on the bullets, which i assume is a rigid body 2d):

extends RigidBody2D

var start = Vector2.ZERO
var direction = Vector2.ZERO
var max = 50 # adjust this in distance

func _ready():
    start = position

func _physics_process():
    position += direction
    var dist = abs(cartesian2polar(position - startpos).x)
    if dist > max:
        self.queue_free()

or alternitavely, you can set a timer and queue free on timeout.

example:

extends RigidBody2D

var start = Vector2.ZERO
var direction = Vector2.ZERO
var maxtime = 2.0 # adjust this in seconds

func _ready():
    var timer = Timer.new()
    timer.wait_time = maxtime
    timer.autostart = true
    add_child(timer)
    timer.connect("timeout", self, "on_timeout")

func on_timeout():
    self.queue_free()

func _physics_process():
    position += direction

oh, and in the case that you dont know, queue_free() just deletes the node.

dustin | 2020-07-28 06:24

Just an addition on the queue_free() topic:
Use call_deferred(‘free’) instead of queue_free

ChristianSF | 2020-07-28 07:35