"call_deferred" not working

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

hi this is my first question so pardon me for any mistakes

i’m trying to make an asteroids clone following this tutorial
i’ve setup two scenes “laser” and “asteroid” each with a script attached to their root nodes

here are the important bits

laser.gd

func _on_laser_body_shape_entered(body_id, body, body_shape, area_shape):
	if (body.is_in_group("asteroids")):
		print("asteroid hit")
		body.call_deferred("explode")
		get_parent().remove_child(self)
		queue_free()

asteroid.gd

var is_exploded := false

func explode():
	print("called exploded")

	if is_exploded:
		return
	is_exploded = true

	get_parent().remove_child(self)
	queue_free()

i only see asteroid hit in the console, can anybody explain me how to use the call_deferred function, or help me fix the code

edit: here are the project files

var is_exploded := false

func explode():
    print("called exploded")

    if is_exploded:
        return
    is_exploded = true

    get_parent().remove_child(self)
    queue_free()

That’s uhhh pretty hacky code. I suggest following a different tutorial.

 func explode():
    print("called exploded")
    queue_free()

That’s what the code should look like. If he’s planning on incrementing a score then he should check is_queued_for_deletion() instead of maintaining his own is_exploded variable. It doesn’t seem like the person that makes that tutorial is well versed in Godot.

timothybrentwood | 2021-05-05 13:19

:bust_in_silhouette: Reply From: MagnusS
get_parent().remove_child(self)

Is redundant. Queue_free() already does that. Other than that, can you post the node layout of your asteroid? I guess, your asteroid.gd is not attached to a KinematicBody node?

here is the asteroid node structure: https://photos.app.goo.gl/j8ATWnnZ5ZxvGMLw8
the root node is a RigidBody2D node btw

edit: i also noticed when the asteroid gets really close to the ship and two lasers are spawned inside the asteroid, the game crashes

tshrpl | 2021-05-05 13:07

I think your error is the “:=” in

var is_exploded := false

It should be a normal “=”. Your var probably has the default value true.

MagnusS | 2021-05-05 13:34

“=” does not change anything :frowning:
i’ve added the project files for you to check

tshrpl | 2021-05-05 13:44

:bust_in_silhouette: Reply From: MagnusS

Found the answer. The problem is in your project structure. Your first asteroid has a “world.gd” script attached to it, not an “asteroid.gd”. This script has no “explode()” method. So as long as this first asteroid is the only asteroid in the world, the deferred call will never fire.

The world script should probably be attached to the “asteroids” node instead.

thank you so much <3

tshrpl | 2021-05-08 08:32