0 votes

Hello.
What I'm trying to achieve is to have the player to launch let's say a simple rigid body sphere with a mouse click and upon launching a new instance the previous one gets removed from the scene so that there is always a single sphere instance in the scene.
Right now I already have the launching part working, however I cannot figure out how to despawn the previously created instance from the scene, so I have them all just accumulating in the scene.
This is my current function to create and impulse launch the sphere, only need to figure out how to remove the previously created instance (obviously the "queue_free" line doesn't really work having it in the same function, so I commented it out:

func _launchProjectile():

if Input.is_action_just_pressed("mouse1") and enableLaunching:
    var p = projectile.instance()
    rayCastPos = get_global_transform().origin
    p.global_transform.origin = Vector3(rayCastPos)
    get_tree().get_root().add_child(p)
    p.apply_central_impulse(global_transform.basis.z*-launch_power)
    #p.queue_free()
Godot version 3.4.4
in Engine by (15 points)

1 Answer

+1 vote
Best answer

It sounds like you just want to retain a reference to the "previous" projectile and remove it once you've created a new one. Something like the below should do that.

var prev_projectile = null

func _launchProjectile():

    if Input.is_action_just_pressed("mouse1") and enableLaunching:
        var p = projectile.instance()
        rayCastPos = get_global_transform().origin
        p.global_transform.origin = Vector3(rayCastPos)
        get_tree().get_root().add_child(p)
        p.apply_central_impulse(global_transform.basis.z*-launch_power)
        if prev_projectile:
            prev_projectile.queue_free()
        prev_projectile = p
by (14,748 points)
selected by

That's it! That did the trick.
Thank you very much!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.