Detecting an entered body

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

The player character I created is able to cast spells, so I want to make enemies die whenever they are hit, but for some reason I can’t get that to work.

I used the _on_Area2D_body_entered signal and created this:

func _on_Area2D_body_entered(body):
		if body.name == "Greenslime":
			greenslime.dead(50)
			print("greenslimehit")
		else:
			queue_free()

My question is what body.name should be equal to because it doesn’t seem to detect “greenslime” which is the name of the kinematicbody used in the greenslime scene!

Is “greenslime” capital or lowercase? When typing in the enemies name, the name has to be exactly what it’s called in the node.

For example, if I have a player and the name is “Player” you have to say

if body.name == "Player":

If you use a lowercase “p”, it won’t work.

rahsut | 2020-08-23 14:27

Thank you for the quick reply!
The scene is named “greenslime” but the kinematicbody is called “Greenslime”

Dexter_ | 2020-08-23 14:29

I’d add a…

print(body.name)

as the first line in ...body_entered() method to see what is being hit. That should shed some light on the problem…

jgodfrey | 2020-08-23 14:44

GREAT idea! I just did and it seems like it was “greenslime”!

Dexter_ | 2020-08-23 14:50

Just another side question, I preloaded the greenslime scene into a constant, and then did the .instance() of it in a variable, but by doing greenslime.dead() in the _on_Area2D_body_entered(body) function nothing happened, however by doing body.dead() inside _on_Area2D_body_entered(body) it worked, what’s the difference?

(also, by doing body.dead i could remove the preoload and everything still works)

Dexter_ | 2020-08-23 14:56

So, in the _on_Area2D_body_entered() method, body contains a reference to the specific body instance that was contacted. So, in that method, you want to use body to reference that instance.

Without seeing some code, I’m just guessing, but I assume the the greenslime instance you created “manually” via .instance() (in your above example) is a different, separate instance of the same scene. So, calling dead() on that instance should work (for that instance), it will not impact any other instance.

So, bottom line, I assume you have (at least) 2 independent greenslime instances in the scene in your test. Interacting with one will not impact the other.

jgodfrey | 2020-08-23 15:36