0 votes

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!

asked Jan 21, 2019 in Engine by Rob1980 (70 points)

1 Answer

+1 vote
Best answer

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.

answered Jan 21, 2019 by p7f (2,666 points)
selected Jan 21, 2019 by Rob1980

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

You are welcome!

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 How to use this Q&A? before posting your first questions.