Character moving with player moved platforms

Hello,

I have a question that I’m stuck on. I have an idea where the player can control both a character and a train. I can move them independently, but I’m having trouble with a specific part.

I want the character to move with the train when it’s on it. When the train is moving but the character is not, the character should play the idle animation. Additionally, I want the character to move independently on the train as it moves, but still move with the train. (I hope you understand what I mean.) So it’s like a platform the player can move by itself.

My initial idea was to create a signal from the train to the character to indicate that the character is on the train and should move with the train’s speed in addition to its own speed. However, I ran into an issue because the character and train are in two different scenes, and I prefer them to be sibling scenes, since I want to make multiple levels and then I can place them independently. I used the following line of code in the character script:
var trainNode = get_tree().get_root().find_node(“/root/game/TestTrain”, true, false)
But I got the error: “Invalid call. Nonexistent function ‘find_node’ in base ‘Window’.”

How do I solve this? Or am I on a completely wrong path to achieve my goal?

Here is some extra information that might help:

The character is a CharacterBody2D with AnimatedSprite2D and CollisionShape2D.
The train is an AnimatableBody2D with AnimatedSprite2D, CollisionShape2D (can’t enter from the front), and an Area2D with a CollisionPolygon2D that detects the player entering the train (this part works).

find_child is the function you are looking for, but I think you can just use get_node without getting the tree since you specify a absolute root path.

var trainNode = get_node("/root/game/TestTrain")
# equivalent to
var trainNode = get_tree().root.get_node("game/TestTrain")

Another way to handle it would be something like this:

If you think you might have other vehicles create a vehicle class and have train inherit from it

In player add a public vehicle variable, or if you really only want speed you could just do a float.

On the collision train will get player as the node of the collision, so you can set it to itself/its speed.