How to make Camera2D follow an instanced node?

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

I have a Player node that doesn’t have any children until runtime. At runtime, the player is given a RigidBody2D child that I want the game’s camera to follow. Putting the Camera2D as a child of Player won’t work because the Player’s position does not change, only its RigidBody2D child’s does. Any ideas?

:bust_in_silhouette: Reply From: supper_raptor

I think you can reparent camera and add child to RigidBody2D.

var cam = $Camera2D
cam.current = true

And to switch camera to player

var cam = $RigidBody2D.get_node("Camera2D")
cam.current = true
:bust_in_silhouette: Reply From: supper_raptor

Alternatively you can add Camera2D to both Player and RigidBody2D

To switch camera to RigidBody2D

$RigidBody2D/Camera2D.current = true

To switch camera to Player

$Camera2D.current = true