This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
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!

in Engine by (96 points)

1 Answer

+1 vote
Best answer

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():

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.

by (3,505 points)
selected by

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 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.