Problem with RigidBody2D

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

Hi everyone! Today I have a problem with RigidBody2D and its interaction with other objects.
So, I have an Area2D bullet and a RigidBody2D enemy. I would like, when the bullet hits the enemy, the enemy disappears. So I connected the body entered () function of the enemy, and I tried to implement the following code:

func _on_enemy_body_entered (body):
          if body.get_name () == "bullet"
              queue_free ()

But it doesn’t work. What am I doing wrong? Thank you!

:bust_in_silhouette: Reply From: p7f

Hi,
In first place, you should not rely on the body name. Names are unique in godot, so when you isntance the first bullet, it may get the name “bullet”, but when you instance a second one with the previous still alive, you will get something like “@bullet@2” or whatever, and the if condition won’t work. You can add to the bullet a variable called for example im_bulletand then ask if "im_bullet" in body.

Second, i prefer to use _on_body_entered in the bullet, and make a function, lets say die() to enemy. So you connect bullets body_entered signal to a function in bullet’s script, and if its an enemy, you call die from them. I like it better that way, aldthough i cannot say is better. Also, i DONT think body entered detects area (i think Area2D isn’t body). That’s why i tend to do this way.

Lastly, in larger scense, its more organized to add nodes to groups. Let say that in ready function of your enemy, you add it to “enemy” group:

func _ready():
    add_to_group("enemy")

Then, in your bullet script you check:

func _on_Bullet_body_entered (body):
      if body.is_in_group("enemy")
          body.queue_free ()

I’ve tested all of this and works in my pc. If it does not work in your, check connections or share me the project and i’ll see.

YEESSS, IT WORKS! Ok, it’s official: you’re my personal super-hero! Thank you so much! :wink:

Rob1980 | 2019-01-21 17:35

You are welcome!

p7f | 2019-01-21 17:37