r/godot•
ltllama

Grabbing a child node of a grandparent node?

tech support - open

Hey I'm new to Godot and working on a 2D game. I'm wondering if there's an easier way to grab the child node of a grandparent node. I tried looking around and couldn't find much around grandparent nodes, so I'm thinking I'm way off base or searching for the wrong thing. I tried looking at Z-ordering but I was still encountering some weirdness.

I have a game scene structured like so

Game
    Camera2D
    Player
    Enemy1
	    HealthComponent
    Enemy2
	    HealthComponent

When one of the enemies have their HP reach zero, I want the health component to delete the enemy and spawn a heart pickup where the enemy was. To do this I was just doing get_parent().get_parent().add_child(heart). This worked fine except the heart pickups show in front of the other enemy due to being the last node in our tree. To remedy this, I added a node between player and enemy where I can add these pickups as children, this would guarantee them to be drawn after the player and before the enemy. The game scene now looks like so:

Game
    Camera2D
    Player
    PickupHolder
    Enemy1
	    HealthComponent
    Enemy2
	    HealthComponent

Now I gave the PickupHolder a unique identifier and then grab the node like so:

if health <= 0.0:
			died.emit()
			get_parent().queue_free()
			var heart = HEART_SCENE.instantiate()
			get_parent().get_parent().get_node("%PickupHolder").add_child(heart)
    			heart.global_position = global_position            

While this works, heart pickup are added as children to the correct node and are drawn in the way I expect, this seems like a very long way to go about grabbing that node. Is there something different I should be doing to grab this? Maybe I should be structuring my game scene in a different manner.

Posted Apr 24, 2024, 4:31 AM UTC

113

Comments aren't archived yet

This post had 13 comments on Reddit. Comments for this period haven't been loaded into the archive yet.