If body is Class not working

Godot Version

v4.3.stable

Question

For a few weeks i’ve been working on a fun little game to learn gdscript. And I’ve usually been able to solve any problems through searching, but I’ve not been able to figure this one out.

So I’ve got a player scene I’ve defined the Characterbody2D’s parent, a Node2D, as “Player” with class_name Player. Then in another scene which is another Node2D with an Area2D I’ve added a script which is supposed to make an E appear over the character when the Player is close. So I’ve used on_body_entered and on_body_exited with these functions:


func _on_area_2d_body_exited(body: Node2D) -> void:
	print("exited")
	if body is Player:
		playerIsInRange = false
		print("playerNotEntered")
		eButton.visible = false



func _on_area_2d_body_entered(body: Node2D) -> void:
	print("entered")
	if body is Player:
		playerIsInRange = true
		print("playerEntered")
		eButton.visible = true

I’ve added print statements to check where the code gets, and the first print statement fires, but the second doesn’t. I’ve deleted and moved the class_name Player many times and it hasn’t worked so far. Does anyone know what could be wrong.
I can add more of the code if needed

Can you print the body.name instead of it and then see what entering the area.

One more question, is the player has collision and is all masks/layers same?

Wait what you said? Is the player script attached with CharacterBody2D or its parent (the Node2D)? If so then it will not work as that Node2D has no collision.

yeah kgd is right. try getting the body’s parent and casting that to your player class instead.

Yeah I probably worded that poorly. I’d tried moving the script from the CharacterBody2D to the Node2D while trying to figure this out. But i must have been doing something wrong before i moved it cause it works now. Thanks a lot :slight_smile:

1 Like