How to get to a collided object's child node?

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

I have Object1 of type Area2D and Object2 of type Area2D.

Object1 has the following function (attached to a signal area_entered(area; Area2D):

# This function handles collisions between objects (Area2Ds)
func bounce_from_area(var who):
    hit_object = who

now hit_object is a global variable in Object1. So whenever Object2 (Area2D) collides with my Object1, Object1 stores the collided object in hit_object variable.

So let’s say Object1 was hit by Object2. Now Object1.hit_object stores Area2D object. If I use I would get “Object2” name). All is fine up to this point.

Now I’d like to get to the child of Object2 stored in hit_object variable. But I can’t.

The below code doesn’t work:

var temp1 = hit_object.AnimatedSprite.animation

I get the following error:

Invalid get index 'AnimatedSprite' (on base: 'Area2D (').
:bust_in_silhouette: Reply From: klaas

you need to use get_node()

var temp1 = hit_object.get_node("AnimatedSprite").current_animation

Yes, it’s working! Thank you!

Can you explain why it’s working?

I mean, intuitively I wanted to use:

var temp1 = who.AnimatedSprite.animation

but it reports error about Area2D node.

The below code is working:

temp1 = who.get_node("AnimatedSprite").animation

I often use dot notation to refer to child nodes, but this time I need to use get_node(), why?

Elendir | 2020-09-11 19:50

Child nodes are not class members, they are managed through the scenen tree.
When you use the dot syntax you try to access a class member.

Get_node gets child nodes from the scenen tree using a nodePath.

You should check the docs for NodePath, its an essential part of working with godot.
Node — Godot Engine (stable) documentation in English

klaas | 2020-09-11 21:25

Thank you! All is clear now.

Elendir | 2020-09-12 14:58